From 8c6e0b49cb502f2baa9db6e8ea577110a8fcedab Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Fri, 4 Dec 2026 14:58:43 +0800 Subject: [PATCH 01/24] Refactor type checks for arrays and mixed types in ParamChecker, ReturnChecker, and DocblockParser; add tests for bare array enforcement and fix bug for bare array type-checking --- src/Internal/Checker/ParamChecker.php | 9 +- src/Internal/Checker/ReturnChecker.php | 7 +- src/Internal/Docblock/DocblockParser.php | 58 +++- src/Internal/RuntimeTypeChecker.php | 4 +- .../BareArrayEnforcementTest.php | 314 ++++++++++++++++++ 5 files changed, 368 insertions(+), 24 deletions(-) create mode 100644 tests/TypeChecking/ArraysAndShapes/BareArrayEnforcementTest.php diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index a43c7415..96b3a692 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -243,16 +243,11 @@ public static function areAllParamsUnconstrained(string $effectiveFunction): boo } /** - * Checks if a TypeNode represents an unconstrained type (mixed or array). + * Checks if a TypeNode represents an unconstrained type (mixed). */ private static function isUnconstrained(TypeNode $typeNode): bool { - if (! ($typeNode instanceof IdentifierTypeNode)) { - return false; - } - $lower = strtolower($typeNode->name); - - return $lower === 'mixed' || $lower === 'array'; + return $typeNode instanceof IdentifierTypeNode && strtolower($typeNode->name) === 'mixed'; } /** diff --git a/src/Internal/Checker/ReturnChecker.php b/src/Internal/Checker/ReturnChecker.php index 5ed0ffcd..eb7cfbb4 100644 --- a/src/Internal/Checker/ReturnChecker.php +++ b/src/Internal/Checker/ReturnChecker.php @@ -409,7 +409,10 @@ private static function evaluateReturn( if ($resolvedType instanceof IdentifierTypeNode) { $name = $resolvedType->name; - if ($name === 'mixed' || $name === 'array' || strtolower($name) === 'mixed' || strtolower($name) === 'array') { + if ($name === 'mixed' || strtolower($name) === 'mixed') { + return $value; + } + if (($name === 'array' || strtolower($name) === 'array') && \is_array($value)) { return $value; } } @@ -553,7 +556,7 @@ private static function evaluateReturn( if ($resolvedType instanceof IdentifierTypeNode) { $lower = strtolower($resolvedType->name); - if ($lower === 'mixed' || $lower === 'array') { + if ($lower === 'mixed' || ($lower === 'array' && \is_array($value))) { return $value; } } diff --git a/src/Internal/Docblock/DocblockParser.php b/src/Internal/Docblock/DocblockParser.php index d173972f..84c365e7 100644 --- a/src/Internal/Docblock/DocblockParser.php +++ b/src/Internal/Docblock/DocblockParser.php @@ -291,16 +291,26 @@ public static function typeReferencesTemplate(?TypeNode $node, array $templateNa } /** - * Checks if a TypeNode represents an unconstrained type (mixed or array). + * Checks if a native PHP reflection type is a non-nullable `array`. */ - private static function isUnconstrainedType(TypeNode $typeNode): bool + private static function isNativeNonNullArrayType(?\ReflectionType $type): bool + { + return $type instanceof \ReflectionNamedType + && strtolower($type->getName()) === 'array' + && ! $type->allowsNull(); + } + + /** + * Checks if a TypeNode represents an unconstrained type (mixed, or bare array when natively guaranteed). + */ + private static function isUnconstrainedType(TypeNode $typeNode, bool $isNativelyNonNullArray = false): bool { if (! ($typeNode instanceof IdentifierTypeNode)) { return false; } $lower = strtolower($typeNode->name); - return $lower === 'mixed' || $lower === 'array'; + return $lower === 'mixed' || ($isNativelyNonNullArray && $lower === 'array'); } /** @@ -308,6 +318,7 @@ private static function isUnconstrainedType(TypeNode $typeNode): bool * @param array $aliases * @param array $methodTemplates * @param array $allTemplates + * @param array $nativeArrayParams * * @return array{ * constrainedTypes: array, @@ -331,7 +342,9 @@ private static function computeContractFlags( array $methodTemplates, bool $paramsAreDynamic = false, array $allTemplates = [], - bool $returnIsThis = false + bool $returnIsThis = false, + array $nativeArrayParams = [], + bool $isNativeArrayReturn = false ): array { $constrainedTypes = []; $paramConditionals = []; @@ -341,7 +354,7 @@ private static function computeContractFlags( if (! ($tNode instanceof IdentifierTypeNode) && ConditionalChecker::containsConditional($tNode)) { $paramConditionals[$paramName] = true; $constrainedTypes[$paramName] = $tNode; - } elseif (! self::isUnconstrainedType($tNode)) { + } elseif (! self::isUnconstrainedType($tNode, isset($nativeArrayParams[$paramName]))) { $constrainedTypes[$paramName] = $tNode; } @@ -368,8 +381,7 @@ private static function computeContractFlags( $returnUnconstrained = false; $returnHasConditional = false; if ($returnType instanceof IdentifierTypeNode) { - $lower = strtolower($returnType->name); - $returnUnconstrained = ($lower === 'mixed' || $lower === 'array'); + $returnUnconstrained = self::isUnconstrainedType($returnType, $isNativeArrayReturn); } elseif ($returnType !== null) { $returnHasConditional = ConditionalChecker::containsConditional($returnType); } @@ -1128,6 +1140,15 @@ private static function parseMethod(\ReflectionMethod $ref, ?\ReflectionClass $t $returnIsDynamic = $returnIsThis || str_contains($retStr, 'static') || str_contains($retStr, '$this'); } + /** @var array $nativeArrayParams */ + $nativeArrayParams = []; + foreach ($ref->getParameters() as $p) { + if (! $p->isVariadic() && self::isNativeNonNullArrayType($p->getType())) { + $nativeArrayParams[$p->getName()] = true; + } + } + $isNativeArrayReturn = self::isNativeNonNullArrayType($ref->getReturnType()); + $flags = self::computeContractFlags( $types, $returnType, @@ -1137,7 +1158,9 @@ private static function parseMethod(\ReflectionMethod $ref, ?\ReflectionClass $t $methodTemplates, $paramsAreDynamic, $allTemplates, - $returnIsThis + $returnIsThis, + $nativeArrayParams, + $isNativeArrayReturn ); return [ @@ -1195,14 +1218,21 @@ private static function parseFunction(\ReflectionFunction $ref): array $baseParamNames = []; $baseParamVariadic = []; $baseParamObjects = []; + /** @var array $nativeArrayParams */ + $nativeArrayParams = []; foreach ($baseParams as $idx => $p) { - $baseParamNames[$idx] = $p->getName(); - $baseParamVariadic[$p->getName()] = $p->isVariadic(); - $baseParamObjects[$p->getName()] = $p; + $pName = $p->getName(); + $baseParamNames[$idx] = $pName; + $baseParamVariadic[$pName] = $p->isVariadic(); + $baseParamObjects[$pName] = $p; + if (! $p->isVariadic() && self::isNativeNonNullArrayType($p->getType())) { + $nativeArrayParams[$pName] = true; + } if (self::hasSensitiveAttribute($p)) { - $sensitiveParams[$p->getName()] = true; + $sensitiveParams[$pName] = true; } } + $isNativeArrayReturn = self::isNativeNonNullArrayType($ref->getReturnType()); if ($doc === false || self::shouldIgnoreDoc($doc)) { return [ @@ -1346,7 +1376,9 @@ private static function parseFunction(\ReflectionFunction $ref): array $templates, false, $templates, - $returnIsThis + $returnIsThis, + $nativeArrayParams, + $isNativeArrayReturn ); return [ diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index b69a8f11..76dd29eb 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -2370,9 +2370,9 @@ public static function checkReturn(string $function, mixed $value, object|string || ($tName === 'string' && \is_string($value)) || ($tName === 'bool' && \is_bool($value)) || ($tName === 'float' && (\is_float($value) || \is_int($value))) + || ($tName === 'array' && \is_array($value)) || (\is_object($value) && ($value instanceof $tName) && ! ($value instanceof Traversable)) || $tName === 'mixed' - || $tName === 'array' ) { return $value; } @@ -2478,7 +2478,7 @@ public static function checkReturn(string $function, mixed $value, object|string if ($resolvedType instanceof IdentifierTypeNode) { $lowerName = strtolower($resolvedType->name); - if ($lowerName === 'mixed' || $lowerName === 'array') { + if ($lowerName === 'mixed') { ReturnChecker::$noReturnContractCache[$effectiveFunction] = true; $unconstrainedPlan = [ 'class' => $declaringClass, diff --git a/tests/TypeChecking/ArraysAndShapes/BareArrayEnforcementTest.php b/tests/TypeChecking/ArraysAndShapes/BareArrayEnforcementTest.php new file mode 100644 index 00000000..38347a3e --- /dev/null +++ b/tests/TypeChecking/ArraysAndShapes/BareArrayEnforcementTest.php @@ -0,0 +1,314 @@ +value : $override; + } +} + +/** + * @phpstan-type BareArrayAlias array + */ +final class BareArrayAliasHolder +{ + /** + * @param BareArrayAlias $payload + */ + public function accept(mixed $payload): void + { + } + + /** + * @return BareArrayAlias + */ + public function produce(mixed $val): mixed + { + return $val; + } +} + +/** + * @method mixed acceptPayload(array $data) + * @method array fetchPayload(mixed $val) + */ +final class BareArrayMagicCaller +{ + /** + * @param array $args + */ + public function __call(string $name, array $args): mixed + { + return $args[0] ?? null; + } +} + +describe('Bare array PHPDoc Contract Enforcement', function () { + describe('Parameter Contracts (@param array)', function () { + test('accepts valid arrays (empty, list, associative)', function () { + testBareArrayUntypedParam([]); + testBareArrayUntypedParam([1, 2, 3]); + testBareArrayUntypedParam(['a' => 1]); + testBareArrayMixedParam(['k' => 'v']); + testBareArrayWithConstrainedParam(1, ['ok' => true]); + testBareArrayUppercaseParam([1]); + + expect(true)->toBeTrue(); + }); + + test('throws TypeError when non-array is passed to untyped @param array', function () { + expect(fn () => testBareArrayUntypedParam(123)) + ->toThrow(TypeError::class, 'Argument $data must be of type array') + ; + + expect(fn () => testBareArrayUntypedParam('not-an-array')) + ->toThrow(TypeError::class, 'Argument $data must be of type array') + ; + + expect(fn () => testBareArrayUntypedParam(null)) + ->toThrow(TypeError::class, 'Argument $data must be of type array') + ; + }); + + test('throws TypeError when non-array is passed to native mixed @param array', function () { + expect(fn () => testBareArrayMixedParam(42)) + ->toThrow(TypeError::class, 'Argument $data must be of type array') + ; + }); + + test('throws TypeError when bare array param is paired with another constrained param (cold and warm)', function () { + testBareArrayWithConstrainedParam(1, ['valid']); + + expect(fn () => testBareArrayWithConstrainedParam(2, 'not-an-array')) + ->toThrow(TypeError::class, 'Argument $data must be of type array') + ; + }); + + test('throws TypeError for case-insensitive @param ARRAY', function () { + expect(fn () => testBareArrayUppercaseParam(false)) + ->toThrow(TypeError::class, 'Argument $data must be of type ARRAY') + ; + }); + }); + + describe('Return Contracts (@return array)', function () { + test('accepts valid array returns', function () { + expect(testBareArrayUntypedReturn([]))->toBe([]); + expect(testBareArrayUntypedReturn(['a' => 1]))->toBe(['a' => 1]); + expect(testBareArrayMixedReturn([1, 2]))->toBe([1, 2]); + expect(testBareArrayUppercaseReturn([]))->toBe([]); + }); + + test('throws TypeError when untyped @return array returns a non-array (cold and warm)', function () { + expect(fn () => testBareArrayUntypedReturn('nope')) + ->toThrow(TypeError::class, 'Return value must be of type array') + ; + + // Second call verifies noReturnContractCache / simpleReturnPlanCache did not bypass validation + expect(fn () => testBareArrayUntypedReturn(123)) + ->toThrow(TypeError::class, 'Return value must be of type array') + ; + }); + + test('throws TypeError when native mixed @return array returns a non-array', function () { + expect(testBareArrayMixedReturn(['ok']))->toBe(['ok']); + + expect(fn () => testBareArrayMixedReturn(new stdClass())) + ->toThrow(TypeError::class, 'Return value must be of type array') + ; + }); + + test('throws TypeError for case-insensitive @return ARRAY', function () { + expect(fn () => testBareArrayUppercaseReturn('nope')) + ->toThrow(TypeError::class, 'Return value must be of type ARRAY') + ; + }); + }); + + describe('Generic Template Bound to array (T = array)', function () { + test('throws TypeError on generic class @return T when T is array (cold ReturnChecker path)', function () { + $box = new BareArrayBox(['key' => 'val']); + + expect(fn () => $box->getCold('not-an-array')) + ->toThrow(TypeError::class, 'Return value must be of type array') + ; + }); + + test('throws TypeError on generic class @return T when T is array (warm genericReturnPlanCache path)', function () { + $box = new BareArrayBox(['key' => 'val']); + + // Populates RuntimeTypeChecker::$genericReturnPlanCache + expect($box->getWarm(true, null))->toBe(['key' => 'val']); + + // Hits cached `$tName === 'array'` fast path + expect(fn () => $box->getWarm(false, 123)) + ->toThrow(TypeError::class, 'Return value must be of type array') + ; + }); + + test('throws TypeError on standalone generic function @return T when T is inferred as array', function () { + expect(testBareArrayGenericReturn(['k' => 'v'], ['other' => 1]))->toBe(['other' => 1]); + + expect(fn () => testBareArrayGenericReturn(['k' => 'v'], 'not-an-array')) + ->toThrow(TypeError::class, 'Return value must be of type array') + ; + }); + }); + + describe('Conditionals, Aliases, and Magic Methods Resolving to array', function () { + test('throws TypeError when conditional @param resolves to bare array', function () { + testBareArrayConditionalParam(true, ['ok']); + testBareArrayConditionalParam(false, 10); + + expect(fn () => testBareArrayConditionalParam(true, 'not-an-array')) + ->toThrow(TypeError::class, 'Argument $val must be of type array') + ; + }); + + test('throws TypeError when conditional @return resolves to bare array', function () { + expect(testBareArrayConditionalReturn(true, ['ok']))->toBe(['ok']); + expect(testBareArrayConditionalReturn(false, 'ok'))->toBe('ok'); + + expect(fn () => testBareArrayConditionalReturn(true, 999)) + ->toThrow(TypeError::class, 'Return value must be of type array') + ; + }); + + test('throws TypeError when type alias resolving to bare array is violated', function () { + $holder = new BareArrayAliasHolder(); + $holder->accept(['ok' => 1]); + expect($holder->produce(['ok' => 1]))->toBe(['ok' => 1]); + + expect(fn () => $holder->accept('not-an-array')) + ->toThrow(TypeError::class, 'Argument $payload must be of type array') + ; + + expect(fn () => $holder->produce(42)) + ->toThrow(TypeError::class, 'Return value must be of type array') + ; + }); + + test('throws TypeError when @method bare array param or return is violated', function () { + $caller = new BareArrayMagicCaller(); + expect($caller->acceptPayload(['ok']))->toBe(['ok']); + expect($caller->fetchPayload(['ok']))->toBe(['ok']); + + expect(fn () => $caller->acceptPayload(123)) + ->toThrow(TypeError::class, 'Argument $data must be of type array') + ; + + expect(fn () => $caller->fetchPayload('not-an-array')) + ->toThrow(TypeError::class, 'Return value must be of type array') + ; + }); + }); +}); From fd5b7d59d243173b35ecc91e9f88fba39e308f86 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Fri, 4 Dec 2026 19:23:07 +0800 Subject: [PATCH 02/24] Refactor ErrorFactory and ViolationCollector to utilize PathMatcher for internal directory checks; add UserInternalDirectoryTraceTest for enhanced violation reporting --- src/Internal/Diagnostic/ErrorFactory.php | 14 +- src/Internal/Reporting/ViolationCollector.php | 4 +- src/Internal/Util/PathMatcher.php | 17 ++ .../UserInternalDirectoryTraceTest.php | 215 ++++++++++++++++++ 4 files changed, 236 insertions(+), 14 deletions(-) create mode 100644 tests/Internal/Diagnostic/UserInternalDirectoryTraceTest.php diff --git a/src/Internal/Diagnostic/ErrorFactory.php b/src/Internal/Diagnostic/ErrorFactory.php index dffded9f..be25d55c 100644 --- a/src/Internal/Diagnostic/ErrorFactory.php +++ b/src/Internal/Diagnostic/ErrorFactory.php @@ -6,17 +6,13 @@ use ReflectionClass; use TypeError; +use TypePHP\Internal\Util\PathMatcher; /** * @internal Factory creating ErrorMessage value objects and preparing TypeError instances with exact caller traces. */ final class ErrorFactory { - private const INTERNAL_DIR_PATTERNS = [ - 'src/Internal/', - 'bin/typephp', - ]; - private const CALL_SITE_KEYWORDS = [ 'argument $', 'argument #', @@ -136,13 +132,7 @@ private static function isInternalFile(string $normalizedFile): bool return false; } - foreach (self::INTERNAL_DIR_PATTERNS as $pattern) { - if (str_contains($normalizedFile, $pattern)) { - return true; - } - } - - return false; + return PathMatcher::isLibraryInternal($normalizedFile); } /** diff --git a/src/Internal/Reporting/ViolationCollector.php b/src/Internal/Reporting/ViolationCollector.php index 23998132..b4affef6 100644 --- a/src/Internal/Reporting/ViolationCollector.php +++ b/src/Internal/Reporting/ViolationCollector.php @@ -13,6 +13,7 @@ use TypePHP\Internal\Io\StreamWrapper; use TypePHP\Internal\Resolver\HierarchyResolver; use TypePHP\Internal\Util\Config; +use TypePHP\Internal\Util\PathMatcher; /** * @internal Manages violation reporting, deduplication, warning dispatch, and parallel test sharding. @@ -825,8 +826,7 @@ private static function collectApplicationFrames(): array $normalizedFile = str_replace('\\', '/', $frame['file']); if ( - str_contains($normalizedFile, 'src/Internal/') - || str_contains($normalizedFile, 'bin/typephp') + PathMatcher::isLibraryInternal($normalizedFile) || str_contains($normalizedFile, 'vendor/phpunit/') || str_contains($normalizedFile, 'vendor/pestphp/') || str_contains($normalizedFile, 'vendor/composer/') diff --git a/src/Internal/Util/PathMatcher.php b/src/Internal/Util/PathMatcher.php index 101e4a1f..e2ff2e60 100644 --- a/src/Internal/Util/PathMatcher.php +++ b/src/Internal/Util/PathMatcher.php @@ -46,6 +46,11 @@ final class PathMatcher */ private static ?string $cachedLibSrcDir = null; + /** + * Cached lowercase TypePHP CLI binary path. + */ + private static ?string $cachedLibBinPath = null; + /** * Cache for canonicalized paths. * @@ -64,6 +69,7 @@ public static function reset(): void self::$canonicalPathCache = []; self::$cachedCacheDir = null; self::$cachedLibSrcDir = null; + self::$cachedLibBinPath = null; CacheManager::reset(); } @@ -204,6 +210,9 @@ public static function isLibraryInternal(string $normalizedPath): bool if (self::$cachedLibSrcDir === null) { $parentDir = realpath(\dirname(__DIR__, 2)); self::$cachedLibSrcDir = $parentDir !== false ? rtrim(self::normalizePath($parentDir), '/') . '/' : ''; + self::$cachedLibBinPath = $parentDir !== false + ? strtolower(rtrim(self::normalizePath(\dirname($parentDir)), '/') . '/bin/typephp') + : ''; } $libSrcDir = self::$cachedLibSrcDir; @@ -215,6 +224,14 @@ public static function isLibraryInternal(string $normalizedPath): bool $lowerCanon = strtolower($canon); $lowerLibSrcDir = strtolower($libSrcDir); + if ( + (self::$cachedLibBinPath !== null && self::$cachedLibBinPath !== '' && $lowerCanon === self::$cachedLibBinPath) + || str_ends_with($lowerCanon, '/vendor/bin/typephp') + || $lowerCanon === 'vendor/bin/typephp' + ) { + return true; + } + if (str_contains($lowerLibSrcDir, '/vendor/')) { return str_starts_with($lowerCanon, $lowerLibSrcDir); } diff --git a/tests/Internal/Diagnostic/UserInternalDirectoryTraceTest.php b/tests/Internal/Diagnostic/UserInternalDirectoryTraceTest.php new file mode 100644 index 00000000..8b698cca --- /dev/null +++ b/tests/Internal/Diagnostic/UserInternalDirectoryTraceTest.php @@ -0,0 +1,215 @@ + $includes, + ]); + + require_once $servicePath; + require_once $callerPath; +}); + +afterEach(function () { + Config::reset(); +}); + +afterAll(function () use (&$userInternalTmpDir, &$userInternalServiceFile, &$userInternalCallerFile) { + Config::reset(); + + if ($userInternalServiceFile !== null && file_exists($userInternalServiceFile)) { + @unlink($userInternalServiceFile); + } + if ($userInternalCallerFile !== null && file_exists($userInternalCallerFile)) { + @unlink($userInternalCallerFile); + } + if ($userInternalTmpDir !== null) { + @rmdir($userInternalTmpDir . '/src/Internal'); + @rmdir($userInternalTmpDir . '/src'); + @rmdir($userInternalTmpDir); + } +}); + +describe('User project src/Internal/ stack traces & violation attribution', function () use (&$userInternalServiceFile, &$userInternalCallerFile) { + test('ErrorFactory preserves user src/Internal/ call-site file, line, and trace on parameter TypeError', function () use (&$userInternalCallerFile) { + $caught = null; + + try { + UserAppInternalTest\Internal\UserCaller::triggerParamViolation(); + } catch (TypeError $e) { + $caught = $e; + } + + expect($caught)->toBeInstanceOf(TypeError::class); + expect(str_replace('\\', '/', $caught->getFile()))->toBe($userInternalCallerFile); + expect($caught->getLine())->toBe(11); + + $traceFiles = array_values(array_filter(array_map( + static fn (array $frame): ?string => isset($frame['file']) ? str_replace('\\', '/', $frame['file']) : null, + $caught->getTrace() + ))); + + expect($traceFiles)->toContain($userInternalCallerFile); + + foreach ($traceFiles as $traceFile) { + expect(PathMatcher::isLibraryInternal($traceFile))->toBeFalse(); + } + }); + + test('ErrorFactory preserves user src/Internal/ caller frame in trace on return TypeError', function () use (&$userInternalServiceFile, &$userInternalCallerFile) { + $caught = null; + + try { + UserAppInternalTest\Internal\UserCaller::triggerReturnViolation(); + } catch (TypeError $e) { + $caught = $e; + } + + expect($caught)->toBeInstanceOf(TypeError::class); + expect(str_replace('\\', '/', $caught->getFile()))->toBe($userInternalServiceFile); + expect($caught->getLine())->toBe(22); + + $traceFiles = array_values(array_filter(array_map( + static fn (array $frame): ?string => isset($frame['file']) ? str_replace('\\', '/', $frame['file']) : null, + $caught->getTrace() + ))); + + expect($traceFiles)->toContain($userInternalCallerFile); + + foreach ($traceFiles as $traceFile) { + expect(PathMatcher::isLibraryInternal($traceFile))->toBeFalse(); + } + }); + + test('ViolationCollector attributes report-mode parameter violations to user src/Internal/ caller', function () use (&$userInternalCallerFile) { + Config::set([ + 'on_violation' => 'report', + 'report_file' => null, + ]); + + UserAppInternalTest\Internal\UserCaller::triggerParamViolation(); + + $violations = ViolationCollector::getViolations(); + + expect($violations)->toHaveCount(1); + expect($violations[0]->file)->toBe($userInternalCallerFile); + expect($violations[0]->line)->toBe(11); + expect($violations[0]->caller)->toContain('src/Internal/UserCaller.php:11'); + }); + + test('ViolationCollector attributes report-mode return violations to user src/Internal/ service and caller', function () use (&$userInternalServiceFile) { + Config::set([ + 'on_violation' => 'report', + 'report_file' => null, + ]); + + UserAppInternalTest\Internal\UserCaller::triggerReturnViolation(); + + $violations = ViolationCollector::getViolations(); + + expect($violations)->toHaveCount(1); + expect($violations[0]->file)->toBe($userInternalServiceFile); + expect($violations[0]->line)->toBe(22); + expect($violations[0]->caller)->toContain('src/Internal/UserCaller.php:16'); + }); + + test('ViolationCollector emits warn-mode warnings pointing to user src/Internal/ call site', function () { + Config::set([ + 'on_violation' => 'warn', + ]); + + $warnings = []; + set_error_handler(static function (int $errno, string $errstr) use (&$warnings): bool { + if ($errno === E_USER_WARNING) { + $warnings[] = $errstr; + + return true; + } + + return false; + }, E_USER_WARNING); + + try { + UserAppInternalTest\Internal\UserCaller::triggerParamViolation(); + } finally { + restore_error_handler(); + } + + expect($warnings)->toHaveCount(1); + expect($warnings[0])->toContain('src/Internal/UserCaller.php on line 11'); + }); +}); From 161496f3e2902839fc818e39fad1d3875a3b78b0 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Fri, 4 Dec 2026 19:46:48 +0800 Subject: [PATCH 03/24] Refactor evaluators to utilize StaticTypeEvaluator for class name resolution; add FullyQualifiedNameEliminationTest for comprehensive coverage of FQCN handling --- .../Evaluator/ConstantAndEnumEvaluator.php | 68 ++-- .../Elimination/Evaluator/ObjectEvaluator.php | 29 +- .../Ast/Elimination/StaticTypeEvaluator.php | 114 ++++++ .../FullyQualifiedNameEliminationTest.php | 352 ++++++++++++++++++ .../UserInternalDirectoryTraceTest.php | 2 +- 5 files changed, 513 insertions(+), 52 deletions(-) create mode 100644 tests/Internal/Ast/Elimination/FullyQualifiedNameEliminationTest.php diff --git a/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php index c0aa4b88..7fbe3321 100644 --- a/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php +++ b/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php @@ -16,7 +16,7 @@ use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; -use TypePHP\Internal\Resolver\SpecialTypeResolver; +use TypePHP\Internal\Ast\Elimination\StaticTypeEvaluator; use UnitEnum; /** @@ -86,10 +86,10 @@ private static function satisfiesClassConst( return false; } - $targetClassName = $fetch->class->toString(); + $targetClassNode = $fetch->class; if ($typeNode instanceof ConstTypeNode && $typeNode->constExpr instanceof ConstFetchNode) { - if (! self::classesMatch($targetClassName, $typeNode->constExpr->className, $currentFile, $currentNamespace)) { + if (! self::classesMatch($targetClassNode, $typeNode->constExpr->className, $currentFile, $currentNamespace)) { return false; } @@ -103,11 +103,11 @@ private static function satisfiesClassConst( } if ($typeNode instanceof IdentifierTypeNode) { - if (! self::classesMatch($targetClassName, $typeNode->name, $currentFile, $currentNamespace)) { + if (! self::classesMatch($targetClassNode, $typeNode->name, $currentFile, $currentNamespace)) { return false; } - $resolvedEnum = self::resolveClassForReflection($targetClassName, $currentFile, $currentNamespace); + $resolvedEnum = self::resolveClassForReflection($targetClassNode, $currentFile, $currentNamespace); if ($resolvedEnum === '' || ! enum_exists($resolvedEnum, false)) { return false; } @@ -118,7 +118,7 @@ private static function satisfiesClassConst( if ($typeNode instanceof GenericTypeNode && strtolower((string) $typeNode->type) === 'int-mask-of') { $inner = $typeNode->genericTypes[0] ?? null; if ($inner instanceof ConstTypeNode && $inner->constExpr instanceof ConstFetchNode) { - if (! self::classesMatch($targetClassName, $inner->constExpr->className, $currentFile, $currentNamespace)) { + if (! self::classesMatch($targetClassNode, $inner->constExpr->className, $currentFile, $currentNamespace)) { return false; } @@ -177,18 +177,18 @@ private static function satisfiesEnumBackingValue( return false; } - $enumClassName = $fetch->var->class->toString(); + $enumClassNode = $fetch->var->class; $caseName = $fetch->var->name->toString(); if (strtolower($caseName) === 'class') { return false; } - if (! self::classesMatch($enumClassName, $enumTarget->name, $currentFile, $currentNamespace)) { + if (! self::classesMatch($enumClassNode, $enumTarget->name, $currentFile, $currentNamespace)) { return false; } - $resolvedEnum = self::resolveClassForReflection($enumClassName, $currentFile, $currentNamespace); + $resolvedEnum = self::resolveClassForReflection($enumClassNode, $currentFile, $currentNamespace); if ($resolvedEnum === '' || ! enum_exists($resolvedEnum, false) || ! is_subclass_of($resolvedEnum, BackedEnum::class)) { return false; } @@ -197,49 +197,53 @@ private static function satisfiesEnumBackingValue( } /** - * Verifies whether two class references deterministically denote the same class/enum. + * Verifies whether an AST class Name node and a PHPDoc class name deterministically denote the same class/enum. */ - private static function classesMatch(string $fetchClass, string $docClass, string $currentFile, ?string $currentNamespace = null): bool + private static function classesMatch(Name $fetchClassNode, string $docClass, string $currentFile, ?string $currentNamespace = null): bool { if ($docClass === '') { return false; } - $lowerFetch = strtolower($fetchClass); + $lowerFetch = strtolower($fetchClassNode->toString()); $lowerDoc = strtolower($docClass); - if ($lowerFetch === 'self' && $lowerDoc === 'self') { - return true; - } - - if (isset(self::RELATIVE_CLASS_KEYWORDS[$lowerFetch]) || isset(self::RELATIVE_CLASS_KEYWORDS[$lowerDoc])) { - return false; - } + if (! $fetchClassNode->isFullyQualified() && ! $fetchClassNode->isRelative()) { + if ($lowerFetch === 'self' && $lowerDoc === 'self') { + return true; + } - if ($fetchClass === $docClass) { - return true; + if (isset(self::RELATIVE_CLASS_KEYWORDS[$lowerFetch])) { + return false; + } } - if ($currentFile !== '') { - $resolvedFetchClass = SpecialTypeResolver::resolveFqcnForFile($fetchClass, $currentFile, false, $currentNamespace); - $resolvedTypeClass = SpecialTypeResolver::resolveFqcnForFile($docClass, $currentFile, false, $currentNamespace); - - return $resolvedFetchClass !== '' && $resolvedFetchClass === $resolvedTypeClass; + if (isset(self::RELATIVE_CLASS_KEYWORDS[$lowerDoc])) { + return false; } - return false; + return StaticTypeEvaluator::classNamesMatch($fetchClassNode, $docClass, $currentFile, $currentNamespace); } /** - * Resolves a class name without invoking autoloading. + * Resolves an AST class Name node to its FQCN without invoking autoloading. */ - private static function resolveClassForReflection(string $rawClass, string $currentFile, ?string $currentNamespace = null): string + private static function resolveClassForReflection(Name $classNode, string $currentFile, ?string $currentNamespace = null): string { - if ($currentFile !== '') { - return SpecialTypeResolver::resolveFqcnForFile($rawClass, $currentFile, false, $currentNamespace); + $resolved = StaticTypeEvaluator::resolveAstClassName($classNode, $currentFile, $currentNamespace); + + if ( + ! $classNode->isFullyQualified() + && ! $classNode->isRelative() + && ! enum_exists($resolved, false) + ) { + $raw = $classNode->toString(); + if (str_contains($raw, '\\') && enum_exists($raw, false)) { + return $raw; + } } - return ltrim($rawClass, '\\'); + return $resolved; } /** diff --git a/src/Internal/Ast/Elimination/Evaluator/ObjectEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/ObjectEvaluator.php index ef7fa80e..4d6e6ab0 100644 --- a/src/Internal/Ast/Elimination/Evaluator/ObjectEvaluator.php +++ b/src/Internal/Ast/Elimination/Evaluator/ObjectEvaluator.php @@ -12,7 +12,7 @@ use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\ThisTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; -use TypePHP\Internal\Resolver\SpecialTypeResolver; +use TypePHP\Internal\Ast\Elimination\StaticTypeEvaluator; /** * Statically evaluates object instantiations and identity returns ($this, new static, new ClassName). @@ -103,33 +103,24 @@ private static function satisfiesNew(Name $classNameNode, TypeNode $typeNode, st $lowerNewClass = strtolower($rawNewClass); $lowerTargetType = strtolower($typeNode->name); - if ($lowerNewClass === 'static' && $lowerTargetType === 'static') { - return true; - } + if (! $classNameNode->isFullyQualified() && ! $classNameNode->isRelative()) { + if ($lowerNewClass === 'static' && $lowerTargetType === 'static') { + return true; + } - if ($lowerNewClass === 'self' && $lowerTargetType === 'self') { - return true; + if ($lowerNewClass === 'self' && $lowerTargetType === 'self') { + return true; + } } if (isset(self::RELATIVE_CLASS_KEYWORDS[$lowerTargetType])) { return false; } - if (isset(self::RELATIVE_CLASS_KEYWORDS[$lowerNewClass])) { + if (! $classNameNode->isFullyQualified() && ! $classNameNode->isRelative() && isset(self::RELATIVE_CLASS_KEYWORDS[$lowerNewClass])) { return false; } - if ($rawNewClass === $typeNode->name) { - return true; - } - - if ($currentFile !== '') { - $resolvedNewClass = SpecialTypeResolver::resolveFqcnForFile($rawNewClass, $currentFile, false, $currentNamespace); - $resolvedTypeClass = SpecialTypeResolver::resolveFqcnForFile($typeNode->name, $currentFile, false, $currentNamespace); - - return $resolvedNewClass !== '' && $resolvedNewClass === $resolvedTypeClass; - } - - return $rawNewClass === $typeNode->name; + return StaticTypeEvaluator::classNamesMatch($classNameNode, $typeNode->name, $currentFile, $currentNamespace); } } diff --git a/src/Internal/Ast/Elimination/StaticTypeEvaluator.php b/src/Internal/Ast/Elimination/StaticTypeEvaluator.php index 0e358d94..9108d273 100644 --- a/src/Internal/Ast/Elimination/StaticTypeEvaluator.php +++ b/src/Internal/Ast/Elimination/StaticTypeEvaluator.php @@ -8,6 +8,7 @@ use PhpParser\Node\Expr\Array_; use PhpParser\Node\Expr\Ternary; use PhpParser\Node\Expr\Variable; +use PhpParser\Node\Name; use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode; use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; @@ -196,4 +197,117 @@ public static function isUnsetSafe(TypeNode $typeNode, array $chain): bool return false; } + + /** + * Resolves a PHP AST Name node to its exact FQCN using strict PHP syntactic name resolution + * rules (without autoloading or global fallback for unqualified names inside a namespace). + */ + public static function resolveAstClassName( + Name $nameNode, + string $currentFile = '', + ?string $currentNamespace = null + ): string { + $raw = $nameNode->toString(); + + if ($nameNode->isFullyQualified()) { + return $raw; + } + + $namespace = $currentNamespace ?? ($currentFile !== '' ? SpecialTypeResolver::getNamespaceFromFile($currentFile) : ''); + + if ($nameNode->isRelative()) { + return $namespace !== '' ? $namespace . '\\' . $raw : $raw; + } + + $imports = $currentFile !== '' + ? SpecialTypeResolver::getUseImportsFromFile($currentFile, $currentNamespace) + : []; + + if (isset($imports[$raw])) { + return $imports[$raw]; + } + + if (str_contains($raw, '\\')) { + [$first, $rest] = explode('\\', $raw, 2); + if (isset($imports[$first])) { + return $imports[$first] . '\\' . $rest; + } + } + + return $namespace !== '' ? $namespace . '\\' . $raw : $raw; + } + + /** + * Deterministically checks whether a PHP AST class Name node and a PHPDoc class name string + * refer to the exact same class or enum in the given file and namespace context. + */ + public static function classNamesMatch( + Name $astClassNode, + string $docClassName, + string $currentFile = '', + ?string $currentNamespace = null + ): bool { + if ($docClassName === '') { + return false; + } + + $docIsFqn = str_starts_with($docClassName, '\\'); + $docTrimmed = ltrim($docClassName, '\\'); + if ($docTrimmed === '') { + return false; + } + + if (! $docIsFqn && SpecialTypeResolver::isBuiltInTypeKeyword($docTrimmed)) { + return false; + } + + if ($currentFile === '') { + if ($astClassNode->isFullyQualified()) { + return $docIsFqn && $astClassNode->toString() === $docTrimmed; + } + + if ($astClassNode->isRelative()) { + if (! $docIsFqn || $currentNamespace === null) { + return false; + } + + $astFqcn = $currentNamespace !== '' + ? $currentNamespace . '\\' . $astClassNode->toString() + : $astClassNode->toString(); + + return $astFqcn === $docTrimmed; + } + + if ($docIsFqn) { + return false; + } + + return $astClassNode->toString() === $docTrimmed; + } + + $resolvedAstClass = self::resolveAstClassName($astClassNode, $currentFile, $currentNamespace); + if ($resolvedAstClass === '') { + return false; + } + + if ($docIsFqn) { + return $resolvedAstClass === $docTrimmed; + } + + $namespace = $currentNamespace ?? SpecialTypeResolver::getNamespaceFromFile($currentFile); + $imports = SpecialTypeResolver::getUseImportsFromFile($currentFile, $currentNamespace); + + if (isset($imports[$docTrimmed])) { + $resolvedDocClass = $imports[$docTrimmed]; + } elseif (str_contains($docTrimmed, '\\')) { + [$first, $rest] = explode('\\', $docTrimmed, 2); + $resolvedDocClass = isset($imports[$first]) + ? $imports[$first] . '\\' . $rest + : ($namespace !== '' ? $namespace . '\\' . $docTrimmed : $docTrimmed); + } else { + $resolvedDocClass = $namespace !== '' ? $namespace . '\\' . $docTrimmed : $docTrimmed; + } + + return $resolvedAstClass === $resolvedDocClass; + } } diff --git a/tests/Internal/Ast/Elimination/FullyQualifiedNameEliminationTest.php b/tests/Internal/Ast/Elimination/FullyQualifiedNameEliminationTest.php new file mode 100644 index 00000000..72aca7d9 --- /dev/null +++ b/tests/Internal/Ast/Elimination/FullyQualifiedNameEliminationTest.php @@ -0,0 +1,352 @@ + + */ + public static function returnGlobalIntMask(): int + { + return \FqnElimConst::FLAG_A; + } + + /** + * @return FqnElimStatus + */ + public static function returnGlobalEnumCase(): mixed + { + return \FqnElimStatus::Active; + } + + /** + * @return value-of + */ + public static function returnGlobalEnumValue(): string + { + return \FqnElimStatus::Active->value; + } + + /** + * @return FqnElimUser + */ + public static function validFqnNew(): mixed + { + return new \FqnElimOther\FqnElimUser(); + } + + /** + * @return \FqnElimOther\FqnElimUser + */ + public static function validImportedNew(): mixed + { + return new FqnElimUser(); + } + + /** + * @return \FqnElimApp\FqnElimUser + */ + public static function validRelativeNew(): mixed + { + return new namespace\FqnElimUser(); + } + + /** + * @return FqnElimConst::STATUS_OK + */ + public static function validFqnConst(): mixed + { + return \FqnElimOther\FqnElimConst::STATUS_OK; + } + + /** + * @return FqnElimStatus + */ + public static function validFqnEnum(): mixed + { + return \FqnElimOther\FqnElimStatus::Active; + } + + /** + * @return value-of + */ + public static function validFqnEnumValue(): string + { + return \FqnElimOther\FqnElimStatus::Active->value; + } +} +PHP); + + file_put_contents($shadowFile, <<<'PHP' + $includes, + 'eliminate_statically_proven_checks' => true, + ]); + + require_once $globalFile; + require_once $otherFile; + require_once $localFile; + require_once $serviceFile; +}); + +afterEach(function () { + Config::reset(); +}); + +afterAll(function () use (&$fqnElimTmpDir, &$fqnElimFiles) { + Config::reset(); + + foreach ($fqnElimFiles as $file) { + if (file_exists($file)) { + @unlink($file); + } + } + + if ($fqnElimTmpDir !== null) { + @rmdir($fqnElimTmpDir); + } +}); + +describe('Compile-Time Elimination with FullyQualified and Relative Class Names', function () use (&$fqnElimAppServiceFile, &$fqnElimShadowFile) { + describe('ObjectEvaluator (new \Foo and new namespace\Foo)', function () use (&$fqnElimShadowFile) { + test('does not eliminate return check when new \FqnElimUser() mismatches imported @return FqnElimUser', function () { + expect(fn () => FqnElimApp\AppService::returnGlobalNew()) + ->toThrow(TypeError::class, 'FqnElimOther\FqnElimUser') + ; + }); + + test('does not eliminate return check when new namespace\FqnElimUser() mismatches imported @return FqnElimUser', function () { + expect(fn () => FqnElimApp\AppService::returnRelativeNew()) + ->toThrow(TypeError::class, 'FqnElimOther\FqnElimUser') + ; + }); + + test('does not treat unimported namespaced new DateTime() as global \DateTime', function () use (&$fqnElimShadowFile) { + $satisfied = StaticTypeEvaluator::satisfies( + new New_(new Name('DateTime')), + new IdentifierTypeNode('\DateTime'), + (string) $fqnElimShadowFile, + [], + 'FqnElimShadow' + ); + + expect($satisfied)->toBeFalse(); + }); + + test('does not match FullyQualified \User against unqualified User without file context', function () { + $satisfied = StaticTypeEvaluator::satisfies( + new New_(new FullyQualified('User')), + new IdentifierTypeNode('User') + ); + + expect($satisfied)->toBeFalse(); + }); + }); + + describe('ConstantAndEnumEvaluator (\Foo::CONST, int-mask-of, enums, value-of)', function () { + test('does not eliminate return check for \FqnElimConst::STATUS_OK against imported FqnElimConst::STATUS_OK', function () { + expect(fn () => FqnElimApp\AppService::returnGlobalConst()) + ->toThrow(TypeError::class) + ; + }); + + test('does not eliminate return check for \FqnElimConst::STATUS_OK against imported FqnElimConst::STATUS_*', function () { + expect(fn () => FqnElimApp\AppService::returnGlobalConstWildcard()) + ->toThrow(TypeError::class) + ; + }); + + test('does not eliminate return check for \FqnElimConst::FLAG_A against imported int-mask-of', function () { + expect(fn () => FqnElimApp\AppService::returnGlobalIntMask()) + ->toThrow(TypeError::class) + ; + }); + + test('does not eliminate return check for \FqnElimStatus::Active against imported FqnElimStatus', function () { + expect(fn () => FqnElimApp\AppService::returnGlobalEnumCase()) + ->toThrow(TypeError::class, 'FqnElimOther\FqnElimStatus') + ; + }); + + test('does not eliminate return check for \FqnElimStatus::Active->value against imported value-of', function () { + expect(fn () => FqnElimApp\AppService::returnGlobalEnumValue()) + ->toThrow(TypeError::class, 'FqnElimOther\FqnElimStatus') + ; + }); + }); + + describe('Legitimate FullyQualified and Relative matches still eliminate checks', function () use (&$fqnElimAppServiceFile) { + test('still eliminates checks when resolved FQCNs genuinely match', function () use (&$fqnElimAppServiceFile) { + expect(FqnElimApp\AppService::validFqnNew())->toBeInstanceOf(FqnElimOther\FqnElimUser::class); + expect(FqnElimApp\AppService::validImportedNew())->toBeInstanceOf(FqnElimOther\FqnElimUser::class); + expect(FqnElimApp\AppService::validRelativeNew())->toBeInstanceOf(FqnElimApp\FqnElimUser::class); + expect(FqnElimApp\AppService::validFqnConst())->toBe('other_ok'); + expect(FqnElimApp\AppService::validFqnEnum())->toBe(FqnElimOther\FqnElimStatus::Active); + expect(FqnElimApp\AppService::validFqnEnumValue())->toBe('other_active'); + + $source = file_get_contents((string) $fqnElimAppServiceFile); + expect($source)->toBeString(); + + $transformed = StreamWrapper::transformSource((string) $source, (string) $fqnElimAppServiceFile); + + foreach (['validFqnNew', 'validImportedNew', 'validRelativeNew', 'validFqnConst', 'validFqnEnum', 'validFqnEnumValue'] as $method) { + $pattern = '/function ' . $method . '\b.*?\{(.*?)\}/s'; + preg_match($pattern, $transformed, $matches); + expect($matches[1] ?? null)->not->toBeNull(); + expect($matches[1])->not->toContain('checkReturn'); + } + }); + }); +}); diff --git a/tests/Internal/Diagnostic/UserInternalDirectoryTraceTest.php b/tests/Internal/Diagnostic/UserInternalDirectoryTraceTest.php index 8b698cca..c782dd98 100644 --- a/tests/Internal/Diagnostic/UserInternalDirectoryTraceTest.php +++ b/tests/Internal/Diagnostic/UserInternalDirectoryTraceTest.php @@ -210,6 +210,6 @@ public static function triggerReturnViolation(): int } expect($warnings)->toHaveCount(1); - expect($warnings[0])->toContain('src/Internal/UserCaller.php on line 11'); + expect(str_replace('\\', '/', $warnings[0]))->toContain('src/Internal/UserCaller.php on line 11'); }); }); From 058ea6e6f95884977210fa7e691bf95adfe509bd Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Fri, 4 Dec 2026 20:04:49 +0800 Subject: [PATCH 04/24] Enhance cloning functionality with exception-safe binding propagation; refactor related methods and tests for PHP 8.5 clone syntax support --- src/Internal/Ast/ContractVisitor.php | 102 ++++++-- src/Internal/Generics/TemplateManager.php | 25 +- src/Internal/RuntimeTypeChecker.php | 90 ++++++- tests/Internal/Ast/ContractVisitorTest.php | 6 +- .../Boundaries/Php85CloneWithTest.php | 8 +- .../Generics/CloneGenericsSoundnessTest.php | 236 ++++++++++++++++++ 6 files changed, 426 insertions(+), 41 deletions(-) create mode 100644 tests/TypeChecking/Generics/CloneGenericsSoundnessTest.php diff --git a/src/Internal/Ast/ContractVisitor.php b/src/Internal/Ast/ContractVisitor.php index 6cdb809c..f1edb21c 100644 --- a/src/Internal/Ast/ContractVisitor.php +++ b/src/Internal/Ast/ContractVisitor.php @@ -801,38 +801,90 @@ public function enterNode(Node $n): ?int private function wrapCloneFunction(Node\Expr\FuncCall $node): ?Node\Expr { - if ($node->getAttribute('typephp_wrapped') === true) { + if ($node->getAttribute('typephp_wrapped') === true || $node->isFirstClassCallable()) { return null; } - $firstArg = $node->args[0] ?? null; - if (! $firstArg instanceof Node\Arg) { + $originalExpr = null; + $propertiesExpr = null; + $positionalIndex = 0; + + foreach ($node->args as $arg) { + if (! ($arg instanceof Node\Arg) || $arg->unpack) { + return null; + } + + if ($arg->name !== null) { + $argName = $arg->name->toString(); + if ($argName === 'object') { + $originalExpr = $arg->value; + } elseif ($argName === 'withProperties') { + $propertiesExpr = $arg->value; + } else { + return null; + } + } else { + if ($positionalIndex === 0) { + $originalExpr = $arg->value; + } elseif ($positionalIndex === 1) { + $propertiesExpr = $arg->value; + } else { + return null; + } + $positionalIndex++; + } + } + + if ($originalExpr === null) { return null; } $node->setAttribute('typephp_wrapped', true); - $originalExpr = $firstArg->value; + if ($propertiesExpr === null) { + $innerClone = new Node\Expr\Clone_(new Node\Expr\Variable('__typephpCloneSrc')); + $innerClone->setAttribute('typephp_wrapped', true); - $secondArg = $node->args[1] ?? null; - $propertiesExpr = $secondArg instanceof Node\Arg - ? $secondArg->value - : new Node\Expr\ConstFetch(new Node\Name('null')); + $clonerArrow = new Node\Expr\ArrowFunction([ + 'static' => true, + 'params' => [new Node\Param(new Node\Expr\Variable('__typephpCloneSrc'))], + 'expr' => $innerClone, + ]); - $node->args[0] = new Node\Arg( - new Node\Expr\FuncCall( - new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::prepareClone'), - [new Node\Arg($originalExpr)], - ), + return new Node\Expr\FuncCall( + new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::executeClone'), + [ + new Node\Arg($originalExpr), + new Node\Arg($clonerArrow), + ] + ); + } + + $innerCloneCall = new Node\Expr\FuncCall( + new Node\Name('clone'), + [ + new Node\Arg(new Node\Expr\Variable('__typephpCloneSrc')), + new Node\Arg(new Node\Expr\Variable('__typephpCloneProps')), + ] ); + $innerCloneCall->setAttribute('typephp_wrapped', true); + + $clonerArrow = new Node\Expr\ArrowFunction([ + 'static' => true, + 'params' => [ + new Node\Param(new Node\Expr\Variable('__typephpCloneSrc')), + new Node\Param(new Node\Expr\Variable('__typephpCloneProps')), + ], + 'expr' => $innerCloneCall, + ]); return new Node\Expr\StaticCall( new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker'), - 'cloneWith', + 'executeCloneWith', [ - new Node\Arg($node), new Node\Arg($originalExpr), new Node\Arg($propertiesExpr), + new Node\Arg($clonerArrow), new Node\Arg(new Node\Scalar\MagicConst\File()), new Node\Arg(new Node\Scalar\LNumber($node->getStartLine())), ], @@ -3002,18 +3054,20 @@ private function wrapClone(Node\Expr\Clone_ $node): ?Node\Expr\FuncCall $node->setAttribute('typephp_wrapped', true); + $innerClone = new Node\Expr\Clone_(new Node\Expr\Variable('__typephpCloneSrc')); + $innerClone->setAttribute('typephp_wrapped', true); + + $clonerArrow = new Node\Expr\ArrowFunction([ + 'static' => true, + 'params' => [new Node\Param(new Node\Expr\Variable('__typephpCloneSrc'))], + 'expr' => $innerClone, + ]); + return new Node\Expr\FuncCall( - new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::cloneInstance'), + new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::executeClone'), [ - new Node\Arg( - new Node\Expr\Clone_( - new Node\Expr\FuncCall( - new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::prepareClone'), - [new Node\Arg($node->expr)] - ) - ) - ), new Node\Arg($node->expr), + new Node\Arg($clonerArrow), ] ); } diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 6a3dbb74..3384c6f0 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -160,10 +160,17 @@ final class TemplateManager private static array $realTypeSymbolCache = []; /** - * Temporary storage for an original object instance being cloned. + * Temporary storage for the top-most original object instance being cloned. */ public static ?object $pendingCloneSource = null; + /** + * Stack of active clone source objects supporting nested clones inside __clone(). + * + * @var list + */ + private static array $pendingCloneStack = []; + /** * Fast boolean flag indicating whether any pending constructor generic instantiations are active. */ @@ -704,6 +711,7 @@ public static function reset(): void self::$subclassCache = []; self::$realTypeSymbolCache = []; self::$pendingCloneSource = null; + self::$pendingCloneStack = []; self::$hasPendingInstantiations = false; self::$methodTemplatesCache = []; self::$isMethodTemplateCache = []; @@ -728,6 +736,21 @@ public static function reset(): void self::$expandedKeyOrValueOfCache = null; } + public static function pushPendingCloneSource(object $original): void + { + self::$pendingCloneStack[] = $original; + self::$pendingCloneSource = $original; + } + + public static function popPendingCloneSource(): ?object + { + $popped = array_pop(self::$pendingCloneStack); + $count = \count(self::$pendingCloneStack); + self::$pendingCloneSource = $count > 0 ? self::$pendingCloneStack[$count - 1] : null; + + return $popped; + } + /** * Restores or clears instance template bindings in WeakMap. * diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index 76dd29eb..d839eedc 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -2971,13 +2971,84 @@ public static function wrapIterable(string $function, string $paramName, mixed $ return IterableWrapper::wrap($function, $paramName, $iterable, self::$registry ??= new TypeValidatorRegistry(), $thisOrClass); } + /** + * Executes a clone expression with single operand evaluation and exception-safe generic binding propagation. + * + * @param \Closure(mixed): mixed $cloner + */ + public static function executeClone(mixed $original, \Closure $cloner): mixed + { + if (! \is_object($original)) { + return $cloner($original); + } + + TemplateManager::pushPendingCloneSource($original); + + try { + $cloned = $cloner($original); + } finally { + TemplateManager::popPendingCloneSource(); + } + + if (\is_object($cloned)) { + TemplateManager::copyInstanceBindings($original, $cloned); + } + + return $cloned; + } + + /** + * PHP 8.5: Executes clone($object, $withProperties) with single argument evaluation, + * exception-safe generic binding propagation, and overridden property validation. + * + * @param \Closure(mixed, mixed): mixed $cloner + */ + public static function executeCloneWith( + mixed $original, + mixed $overriddenProperties, + \Closure $cloner, + string $file = '', + ?int $line = null, + ): mixed { + if (! \is_object($original)) { + return $cloner($original, $overriddenProperties); + } + + TemplateManager::pushPendingCloneSource($original); + + try { + $cloned = $cloner($original, $overriddenProperties); + } finally { + TemplateManager::popPendingCloneSource(); + } + + if (! \is_object($cloned)) { + return $cloned; + } + + TemplateManager::copyInstanceBindings($original, $cloned); + + if (\is_array($overriddenProperties) && $overriddenProperties !== [] && self::$isEnabled && Config::isInlinePropertiesEnabled()) { + foreach ($overriddenProperties as $propName => $propValue) { + $res = self::checkProperty($propValue, $cloned, (string) $propName, $file); + if ($res instanceof ErrorMessage) { + $typeError = new \TypePHP\Exception\TypeError($res->getMessage()); + + throw ErrorFactory::prepareException($typeError, $line, $file !== '' ? $file : null); + } + } + } + + return $cloned; + } + /** * Registers a pending clone source object before clone execution. */ public static function prepareClone(mixed $original): mixed { if (\is_object($original)) { - TemplateManager::$pendingCloneSource = $original; + TemplateManager::pushPendingCloneSource($original); } return $original; @@ -2986,13 +3057,14 @@ public static function prepareClone(mixed $original): mixed /** * Copies generic template bindings from an original object to a cloned object instance. */ - public static function cloneInstance(mixed $cloned, mixed $original): mixed + public static function cloneInstance(mixed $cloned, mixed $original = null): mixed { - if (\is_object($cloned) && \is_object($original)) { - TemplateManager::copyInstanceBindings($original, $cloned); - } + $popped = TemplateManager::popPendingCloneSource(); + $source = \is_object($original) ? $original : $popped; - TemplateManager::$pendingCloneSource = null; + if (\is_object($cloned) && \is_object($source)) { + TemplateManager::copyInstanceBindings($source, $cloned); + } return $cloned; } @@ -3009,8 +3081,8 @@ public static function cloneWith( string $file = '', ?int $line = null, ): mixed { - $source = \is_object($original) ? $original : TemplateManager::$pendingCloneSource; - TemplateManager::$pendingCloneSource = null; + $popped = TemplateManager::popPendingCloneSource(); + $source = \is_object($original) ? $original : $popped; if (! \is_object($cloned) || ! \is_object($source)) { return $cloned; @@ -3018,7 +3090,7 @@ public static function cloneWith( TemplateManager::copyInstanceBindings($source, $cloned); - if ($overriddenProperties !== null && $overriddenProperties !== [] && Config::isInlinePropertiesEnabled()) { + if ($overriddenProperties !== null && $overriddenProperties !== [] && self::$isEnabled && Config::isInlinePropertiesEnabled()) { foreach ($overriddenProperties as $propName => $propValue) { $res = self::checkProperty($propValue, $cloned, (string) $propName, $file); if ($res instanceof ErrorMessage) { diff --git a/tests/Internal/Ast/ContractVisitorTest.php b/tests/Internal/Ast/ContractVisitorTest.php index b0927ed9..d5a23edb 100644 --- a/tests/Internal/Ast/ContractVisitorTest.php +++ b/tests/Internal/Ast/ContractVisitorTest.php @@ -142,7 +142,7 @@ public function set() { ; }); - test('transforms clone expressions into prepareClone and cloneInstance wrappers', function () { + test('transforms clone expressions into executeClone wrappers', function () { $code = <<<'PHP' printer->prettyPrint($newStmts); - expect($transformed)->toContain('RuntimeTypeChecker::cloneInstance') - ->and($transformed)->toContain('RuntimeTypeChecker::prepareClone($original)') + expect($transformed)->toContain('RuntimeTypeChecker::executeClone($original,') + ->and($transformed)->toContain('clone $__typephpCloneSrc') ; }); diff --git a/tests/TypeChecking/Boundaries/Php85CloneWithTest.php b/tests/TypeChecking/Boundaries/Php85CloneWithTest.php index 62b4aab2..c46db42a 100644 --- a/tests/TypeChecking/Boundaries/Php85CloneWithTest.php +++ b/tests/TypeChecking/Boundaries/Php85CloneWithTest.php @@ -22,7 +22,7 @@ describe('PHP 8.5 "Clone With" Syntax Support (TDD)', function () { describe('1. AST Transformation (nikic/php-parser FuncCall interception)', function () { - test('transforms PHP 8.5 clone($obj, [...]) function call into RuntimeTypeChecker::cloneWith wrapper', function () { + test('transforms PHP 8.5 clone($obj, [...]) function call into RuntimeTypeChecker::executeCloneWith wrapper', function () { $source = <<<'PHP' 20]); @@ -30,12 +30,12 @@ $transformed = StreamWrapper::transformSource($source, 'test_clone_with.php'); - expect($transformed)->toContain('RuntimeTypeChecker::cloneWith') + expect($transformed)->toContain('RuntimeTypeChecker::executeCloneWith($order,') ->and($transformed)->toContain('[\'score\' => 20]') ; }); - test('transforms single-argument clone($obj) into RuntimeTypeChecker::cloneInstance wrapper', function () { + test('transforms single-argument clone($obj) into RuntimeTypeChecker::executeClone wrapper', function () { $source = <<<'PHP' toContain('RuntimeTypeChecker::cloneInstance'); + expect($transformed)->toContain('RuntimeTypeChecker::executeClone($order,'); }); }); diff --git a/tests/TypeChecking/Generics/CloneGenericsSoundnessTest.php b/tests/TypeChecking/Generics/CloneGenericsSoundnessTest.php new file mode 100644 index 00000000..8534e9c6 --- /dev/null +++ b/tests/TypeChecking/Generics/CloneGenericsSoundnessTest.php @@ -0,0 +1,236 @@ +value = $value; + } +} + +/** + * @template T + */ +final class CloneOuterBox +{ + public ?string $capturedTypeAfterInnerClone = null; + + /** + * @param T $value + * @param CloneTestBox $inner + */ + public function __construct( + public mixed $value, + public CloneTestBox $inner, + public bool $triggerInvalidAfterInnerClone = false, + ) { + } + + /** + * @param T $value + */ + public function setValue(mixed $value): void + { + $this->value = $value; + } + + public function __clone(): void + { + $this->inner = clone $this->inner; + $this->capturedTypeAfterInnerClone = TypePHP::getGenericType($this); + + if ($this->triggerInvalidAfterInnerClone) { + $this->setValue('definitely-not-an-int'); + } + } +} + +/** + * @template T + */ +final class CloneThrowingBox +{ + /** + * @param T $value + */ + public function __construct(public mixed $value) + { + } + + public function __clone(): void + { + throw new RuntimeException('Clone aborted'); + } +} + +describe('Clone AST Wrapping & Generic Binding Soundness', function () { + test('clone evaluates impure operand expression exactly once and copies bindings from that instance', function () { + $calls = 0; + + $makeBox = function () use (&$calls): CloneTestBox { + $calls++; + + return $calls === 1 + ? new CloneTestBox(42) + : new CloneTestBox('wrong-second-instance'); + }; + + $cloned = clone $makeBox(); + + expect($calls)->toBe(1); + expect(TypePHP::getGenericType($cloned))->toBe('int'); + + $cloned->set(99); + expect($cloned->value)->toBe(99); + + expect(fn () => $cloned->set('invalid-string')) + ->toThrow(TypeError::class) + ; + }); + + test('nested clone inside __clone() preserves outer object generic bindings after inner clone completes', function () { + $outer = new CloneOuterBox(10, new CloneTestBox('inner')); + $cloned = clone $outer; + + expect($cloned->capturedTypeAfterInnerClone)->toBe('int'); + expect(TypePHP::getGenericType($cloned))->toBe('int'); + expect(TypePHP::getGenericType($cloned->inner))->toBe('string'); + }); + + test('nested clone inside __clone() continues enforcing outer generic contracts during __clone()', function () { + $outer = new CloneOuterBox(10, new CloneTestBox('inner'), triggerInvalidAfterInnerClone: true); + + expect(fn () => clone $outer) + ->toThrow(TypeError::class, 'Argument $value') + ; + }); + + test('exception thrown inside __clone() does not leak pending clone source to subsequent instantiations', function () { + $intBox = new CloneThrowingBox(42); + + expect(fn () => clone $intBox) + ->toThrow(RuntimeException::class, 'Clone aborted') + ; + + expect(\TypePHP\Internal\Generics\TemplateManager::$pendingCloneSource)->toBeNull(); + + $strBox = new CloneThrowingBox('hello'); + + expect($strBox->value)->toBe('hello'); + expect(TypePHP::getGenericType($strBox))->toBe('string'); + }); + + test('PHP 8.5 clone($obj, $props) AST transformation evaluates object and properties expressions once', function () { + $source = <<<'PHP' +toBe(1); + expect(substr_count($transformed, 'makeCloneProps()'))->toBe(1); + }); + + test('PHP 8.5 clone($obj, $props) runtime evaluates arguments once, preserves generics, and validates overrides', function () { + $baseTmp = sys_get_temp_dir() . '/typephp_clone_with_' . uniqid('', true); + mkdir($baseTmp, 0777, true); + $realBase = realpath($baseTmp); + $tmpDir = str_replace('\\', '/', $realBase !== false ? $realBase : $baseTmp); + $scriptPath = $tmpDir . '/clone_with_runtime.php'; + + file_put_contents($scriptPath, <<<'PHP' + 7]; +}; + +$cloned = clone($makeObj(), $makeProps()); + +return [ + 'objCalls' => $objCalls, + 'propsCalls' => $propsCalls, + 'genericType' => TypePHP::getGenericType($cloned), + 'count' => $cloned->count, + 'triggerInvalid' => static fn (): mixed => clone($cloned, ['count' => -3]), +]; +PHP); + + $currentIncludes = Config::get()['include'] ?? []; + $includes = \is_array($currentIncludes) ? $currentIncludes : []; + $includes[] = $tmpDir . '/**'; + + Config::set(['include' => $includes]); + + try { + /** @var array{objCalls: int, propsCalls: int, genericType: ?string, count: int, triggerInvalid: Closure(): mixed} $result */ + $result = require $scriptPath; + + expect($result['objCalls'])->toBe(1); + expect($result['propsCalls'])->toBe(1); + expect($result['genericType'])->toBe('int'); + expect($result['count'])->toBe(7); + expect($result['triggerInvalid'])->toThrow(TypeError::class, 'positive-int'); + } finally { + Config::reset(); + @unlink($scriptPath); + @rmdir($tmpDir); + } + })->skip(\PHP_VERSION_ID < 80500, 'Requires PHP 8.5+ clone-with syntax'); +}); From 68953ff216aa6a4c4c4fbd5eb886f8ca9ba1b639 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Fri, 4 Dec 2026 21:00:15 +0800 Subject: [PATCH 05/24] Add tests for return expression evaluation order with @param-out and @self-out post-conditions --- src/Internal/Ast/FunctionContractInjector.php | 79 ++++- ...ReturnExpressionPostConditionOrderTest.php | 288 ++++++++++++++++++ 2 files changed, 353 insertions(+), 14 deletions(-) create mode 100644 tests/TypeChecking/Boundaries/ReturnExpressionPostConditionOrderTest.php diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index cda0b6e9..c0676866 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -1099,6 +1099,44 @@ public static function buildParamOutCheckStmts( return $stmts; } + /** + * Checks whether a return expression is guaranteed side-effect-free and cannot throw or mutate state. + */ + public static function isTrivialPureReturnExpr(Node\Expr $expr): bool + { + return ($expr instanceof Node\Expr\Variable && \is_string($expr->name)) + || $expr instanceof Node\Scalar\LNumber + || $expr instanceof Node\Scalar\DNumber + || $expr instanceof Node\Scalar\String_ + || ($expr instanceof Node\Expr\ConstFetch && \in_array(strtolower($expr->name->toString()), ['true', 'false', 'null'], true)); + } + + /** + * Hoists a non-trivial return expression into a temporary variable so that it executes + * before @self-out and @param-out post-conditions are checked. + * + * @return list + */ + public static function hoistReturnExprForExitChecks(Node\Stmt\Return_ $returnNode, bool $byRef = false): array + { + $originalExpr = $returnNode->expr; + if ($originalExpr === null || self::isTrivialPureReturnExpr($originalExpr)) { + return []; + } + + $retVar = new Node\Expr\Variable('__typephpRetVal'); + $assign = $byRef + ? new Node\Expr\AssignRef($retVar, $originalExpr) + : new Node\Expr\Assign($retVar, $originalExpr); + + $stmt = new Node\Stmt\Expression($assign); + $stmt->setAttribute('typephp_injected', true); + + $returnNode->expr = new Node\Expr\Variable('__typephpRetVal'); + + return [$stmt]; + } + /** * @param array $params * @param callable(Node\Param, ?TypeNode, array): bool $predicate @@ -1979,6 +2017,11 @@ public function enterNode(Node $n): int|Node|array|null $exitStmts = [...$exitStmts, ...$paramOutStmts]; } + $originalExpr = $n->expr; + $preEvalStmts = $exitStmts !== [] + ? FunctionContractInjector::hoistReturnExprForExitChecks($n, false) + : []; + if (FunctionContractInjector::inlineVarSubsumesReturn( $n, $this->genContract['return'] ?? null, @@ -1987,12 +2030,12 @@ public function enterNode(Node $n): int|Node|array|null $this->currentFile, $this->currentNamespace )) { - return $exitStmts !== [] ? [...$exitStmts, $n] : null; + return $exitStmts !== [] ? [...$preEvalStmts, ...$exitStmts, $n] : null; } - $exprToWrap = $n->expr ?? new Node\Expr\ConstFetch(new Node\Name('null')); + $origExprOrNull = $originalExpr ?? new Node\Expr\ConstFetch(new Node\Name('null')); $assignedExpr = $n->getAttribute('typephp_preceding_assign_expr'); - $candidateExpr = ($assignedExpr instanceof Node\Expr) ? $assignedExpr : $exprToWrap; + $candidateExpr = ($assignedExpr instanceof Node\Expr) ? $assignedExpr : $origExprOrNull; if ( ($this->genContract !== null @@ -2005,9 +2048,11 @@ public function enterNode(Node $n): int|Node|array|null )) || ($this->explicitGenContract !== null && $this->explicitGenContract['return'] === null) ) { - return $exitStmts !== [] ? [...$exitStmts, $n] : $n; + return $exitStmts !== [] ? [...$preEvalStmts, ...$exitStmts, $n] : $n; } + $exprToWrap = $n->expr ?? new Node\Expr\ConstFetch(new Node\Name('null')); + $scopeArg = new Node\Expr\BinaryOp\Coalesce( new Node\Expr\Variable('__typephpScope'), new Node\Expr\ConstFetch(new Node\Name('null')) @@ -2025,7 +2070,7 @@ public function enterNode(Node $n): int|Node|array|null $n->expr = FunctionContractInjector::buildTernaryReturnExpr($checkCall, $n->getStartLine()); - return $exitStmts !== [] ? [...$exitStmts, $n] : $n; + return $exitStmts !== [] ? [...$preEvalStmts, ...$exitStmts, $n] : $n; } return null; @@ -2204,8 +2249,13 @@ public function enterNode(Node $n): int|array|null $exitStmts = [...$exitStmts, ...$paramOutStmts]; } + $originalExpr = $n->expr; + $preEvalStmts = $exitStmts !== [] + ? FunctionContractInjector::hoistReturnExprForExitChecks($n, $this->isByRefReturn) + : []; + if (! $this->hasReturn) { - return $exitStmts !== [] ? [...$exitStmts, $n] : null; + return $exitStmts !== [] ? [...$preEvalStmts, ...$exitStmts, $n] : null; } $isReturnElimSafe = ! $this->isByRefReturn @@ -2222,33 +2272,34 @@ public function enterNode(Node $n): int|array|null $this->currentFile, $this->currentNamespace )) { - return $exitStmts !== [] ? [...$exitStmts, $n] : null; + return $exitStmts !== [] ? [...$preEvalStmts, ...$exitStmts, $n] : null; } - $exprToWrap = $n->expr ?? new Node\Expr\ConstFetch(new Node\Name('null')); - + $origExprOrNull = $originalExpr ?? new Node\Expr\ConstFetch(new Node\Name('null')); $assignedExpr = $n->getAttribute('typephp_preceding_assign_expr'); - $candidateExpr = ($assignedExpr instanceof Node\Expr) ? $assignedExpr : $exprToWrap; + $candidateExpr = ($assignedExpr instanceof Node\Expr) ? $assignedExpr : $origExprOrNull; if ( $isReturnElimSafe && StaticTypeEvaluator::satisfies($candidateExpr, $this->returnTypeNode, $this->currentFile, $this->trustedParamTypes, $this->currentNamespace) ) { - return $exitStmts !== [] ? [...$exitStmts, $n] : null; + return $exitStmts !== [] ? [...$preEvalStmts, ...$exitStmts, $n] : null; } + $exprToWrap = $n->expr ?? new Node\Expr\ConstFetch(new Node\Name('null')); + if ($this->isNativeVoid) { $checkCall = FunctionContractInjector::buildReturnCheckCall($exprToWrap, $this->thisArg, $this->needsReturnVars); $voidGuardStmts = FunctionContractInjector::buildVoidReturnGuard($checkCall); - return [...$exitStmts, ...$voidGuardStmts]; + return [...$preEvalStmts, ...$exitStmts, ...$voidGuardStmts]; } if ($this->isByRefReturn) { $checkCall = FunctionContractInjector::buildReturnCheckCall($exprToWrap, $this->thisArg, $this->needsReturnVars); $byRefGuardStmts = FunctionContractInjector::buildByRefReturnGuard($checkCall, $n, $n->getStartLine()); - return [...$exitStmts, ...$byRefGuardStmts]; + return [...$preEvalStmts, ...$exitStmts, ...$byRefGuardStmts]; } if ($this->canGuardReturnCache) { @@ -2267,7 +2318,7 @@ public function enterNode(Node $n): int|array|null ); } - return $exitStmts !== [] ? [...$exitStmts, $n] : null; + return $exitStmts !== [] ? [...$preEvalStmts, ...$exitStmts, $n] : null; } return null; diff --git a/tests/TypeChecking/Boundaries/ReturnExpressionPostConditionOrderTest.php b/tests/TypeChecking/Boundaries/ReturnExpressionPostConditionOrderTest.php new file mode 100644 index 00000000..b5360e28 --- /dev/null +++ b/tests/TypeChecking/Boundaries/ReturnExpressionPostConditionOrderTest.php @@ -0,0 +1,288 @@ + + */ +function testPostCondGenPopulateInReturn(mixed &$out): Generator +{ + $out = 10; + yield 1; + $out = null; + + return postCondSetOutAndReturnString($out, 77); +} + +/** + * @param mixed $out + * + * @param-out positive-int $out + * + * @return Generator + */ +function testPostCondGenCorruptInReturn(mixed &$out): Generator +{ + $out = 10; + yield 1; + + return postCondSetOutAndReturnString($out, -3); +} + +/** + * @param mixed $out + * + * @param-out positive-int $out + * + * @return Generator + */ +function testPostCondGenThrowInReturn(mixed &$out): Generator +{ + $out = 10; + yield 1; + $out = null; + + return postCondThrowString($out); +} +/** + * @template T + */ +final class PostCondSelfOutBox +{ + /** + * @param T $value + */ + public function __construct(public mixed $value) + { + } + + /** + * @return T + */ + public function getValue(): mixed + { + return $this->value; + } + + private function readIntAndRewriteToString(): int + { + $old = $this->getValue(); + $this->value = 'migrated'; + + return \is_int($old) ? $old : 0; + } + + private function throwOnTransition(): string + { + throw new RuntimeException('transition failed'); + } + + /** + * @phpstan-self-out self + */ + public function readOldThenTransition(): int + { + return $this->readIntAndRewriteToString(); + } + + /** + * @phpstan-self-out self + */ + public function failDuringTransition(): string + { + return $this->throwOnTransition(); + } +} + +describe('Return Expression Evaluation Order vs @param-out / @self-out', function () { + describe('Non-generator @param-out post-conditions', function () { + test('evaluates return expression before checking @param-out when return expression populates &$out', function () { + $out = null; + $result = testPostCondPopulateOutInReturn($out); + + expect($result)->toBeTrue(); + expect($out)->toBe(42); + }); + + test('catches @param-out violation when return expression mutates &$out from valid to invalid', function () { + $out = null; + + expect(fn () => testPostCondCorruptOutInReturn($out)) + ->toThrow(TypeError::class, 'Argument &$out (param-out)') + ; + }); + + test('evaluates inline assignment inside return expression before checking @param-out', function () { + $out = null; + expect(testPostCondInlineAssignInReturn($out, 25))->toBe(25); + expect($out)->toBe(25); + + $out = 5; + expect(fn () => testPostCondInlineAssignInReturn($out, -1)) + ->toThrow(TypeError::class, 'Argument &$out (param-out)') + ; + }); + + test('enforces both @param-out and @return after evaluating return expression', function () { + $out = null; + expect(testPostCondBothParamOutAndReturn($out, 15, 99))->toBe(99); + expect($out)->toBe(15); + + $out = null; + expect(fn () => testPostCondBothParamOutAndReturn($out, 15, -1)) + ->toThrow(TypeError::class, 'Return value must be of type positive-int') + ; + }); + + test('does not run @param-out check when return expression throws an exception', function () { + $out = null; + + expect(fn () => testPostCondThrowInReturn($out)) + ->toThrow(RuntimeException::class, 'helper failed') + ; + }); + }); + + describe('@self-out post-conditions', function () { + test('evaluates return expression under pre-transition state before applying @self-out', function () { + $box = new PostCondSelfOutBox(42); + + $old = $box->readOldThenTransition(); + + expect($old)->toBe(42); + expect(TypePHP::getGenericType($box))->toBe('string'); + expect($box->getValue())->toBe('migrated'); + }); + + test('does not apply @self-out transition when return expression throws an exception', function () { + $box = new PostCondSelfOutBox(42); + + expect(fn () => $box->failDuringTransition()) + ->toThrow(RuntimeException::class, 'transition failed') + ; + + expect(TypePHP::getGenericType($box))->toBe('int'); + expect($box->getValue())->toBe(42); + }); + }); + + describe('Generator return expressions with @param-out', function () { + test('evaluates generator return expression before checking @param-out', function () { + $out = null; + $gen = testPostCondGenPopulateInReturn($out); + iterator_to_array($gen); + + expect($gen->getReturn())->toBe('done'); + expect($out)->toBe(77); + }); + + test('catches @param-out violation mutated inside generator return expression', function () { + $out = null; + $gen = testPostCondGenCorruptInReturn($out); + + expect(fn () => iterator_to_array($gen)) + ->toThrow(TypeError::class, 'Argument &$out (param-out)') + ; + }); + + test('does not run @param-out check when generator return expression throws an exception', function () { + $out = null; + $gen = testPostCondGenThrowInReturn($out); + + expect(fn () => iterator_to_array($gen)) + ->toThrow(RuntimeException::class, 'generator helper failed') + ; + }); + }); +}); From 58a16af18e5b3b5d080b32aecec62fa3e007dd5b Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Fri, 4 Dec 2026 21:29:07 +0800 Subject: [PATCH 06/24] Implement contravariance soundness tests for TemplateManager::checkVariance() --- src/Internal/Generics/TemplateManager.php | 129 ++++++------- .../Generics/ContraVarianceSoundnessTest.php | 171 ++++++++++++++++++ 2 files changed, 223 insertions(+), 77 deletions(-) create mode 100644 tests/TypeChecking/Generics/ContraVarianceSoundnessTest.php diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 3384c6f0..96431264 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -3485,6 +3485,26 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str return true; } + if ($variance === GenericTypeNode::VARIANCE_CONTRAVARIANT) { + if ($lowerExisting === 'mixed' || $lowerExisting === '*') { + return true; + } + + if ($lowerExisting === 'object' && ClassNameValidator::isValid($expectedName) && self::isRealTypeSymbol($expectedName)) { + return true; + } + + if (isset(self::SCALAR_SUBTYPES[$lowerExisting][$lowerExpected]) || self::isScalarSubtype($lowerExpected, $lowerExisting)) { + return true; + } + + if (isset(self::COLLECTION_SUBTYPES[$lowerExisting])) { + return isset(self::COLLECTION_SUBTYPES[$lowerExisting][$lowerExpected]); + } + + return self::isSubclass($expectedName, $existingName); + } + if ($lowerExpected === 'object' && ClassNameValidator::isValid($existingName) && self::isRealTypeSymbol($existingName)) { return true; } @@ -3501,10 +3521,6 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str return self::isSubclass($existingName, $expectedName); } - if ($variance === GenericTypeNode::VARIANCE_CONTRAVARIANT) { - return self::isSubclass($expectedName, $existingName); - } - return false; } @@ -3550,6 +3566,13 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str } } + if ($expected instanceof IdentifierTypeNode) { + $lowerExpected = strtolower($expected->name); + if ($lowerExpected === 'mixed' || $lowerExpected === '*') { + return true; + } + } + if ($existing instanceof ConstTypeNode && $expected instanceof ConstTypeNode) { $ok1 = false; $ok2 = false; @@ -3566,20 +3589,24 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str } } + if ($variance === GenericTypeNode::VARIANCE_CONTRAVARIANT) { + return self::checkVariance($expected, $existing, GenericTypeNode::VARIANCE_COVARIANT); + } + if ($expected instanceof UnionTypeNode && $variance !== GenericTypeNode::VARIANCE_INVARIANT) { - return self::checkExpectedUnionVariance($existing, $expected, $variance); + return self::checkExpectedUnionCovariant($existing, $expected); } if ($existing instanceof UnionTypeNode && $variance !== GenericTypeNode::VARIANCE_INVARIANT) { - return self::checkExistingUnionVariance($existing, $expected, $variance); + return self::checkExistingUnionCovariant($existing, $expected); } if ($expected instanceof IntersectionTypeNode && $variance !== GenericTypeNode::VARIANCE_INVARIANT) { - return self::checkExpectedIntersectionVariance($existing, $expected, $variance); + return self::checkExpectedIntersectionCovariant($existing, $expected); } if ($existing instanceof IntersectionTypeNode && $variance !== GenericTypeNode::VARIANCE_INVARIANT) { - return self::checkExistingIntersectionVariance($existing, $expected, $variance); + return self::checkExistingIntersectionCovariant($existing, $expected); } if ($existing instanceof ArrayTypeNode && $expected instanceof ArrayTypeNode) { @@ -3644,10 +3671,6 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str if ($expected instanceof IdentifierTypeNode) { $lowerExpected = strtolower($expected->name); - if ($lowerExpected === 'mixed' || $lowerExpected === '*') { - return true; - } - if ($existing instanceof ArrayTypeNode || $existing instanceof ArrayShapeNode) { if ($variance === GenericTypeNode::VARIANCE_COVARIANT && ($lowerExpected === 'array' || $lowerExpected === 'iterable')) { return true; @@ -3672,11 +3695,11 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str } if ($variance === GenericTypeNode::VARIANCE_COVARIANT) { - return self::isSubclass((string) $existing->type, $expected->name); - } + if ($lowerExpected === 'object' && ClassNameValidator::isValid((string) $existing->type) && self::isRealTypeSymbol((string) $existing->type)) { + return true; + } - if ($variance === GenericTypeNode::VARIANCE_CONTRAVARIANT) { - return self::isSubclass($expected->name, (string) $existing->type); + return self::isSubclass((string) $existing->type, $expected->name); } return false; @@ -3702,19 +3725,19 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str } if ($expected instanceof UnionTypeNode) { - return self::checkExpectedUnionVariance($existing, $expected, $variance); + return self::checkExpectedUnionCovariant($existing, $expected); } if ($existing instanceof UnionTypeNode) { - return self::checkExistingUnionVariance($existing, $expected, $variance); + return false; } if ($expected instanceof IntersectionTypeNode) { - return self::checkExpectedIntersectionVariance($existing, $expected, $variance); + return self::checkExpectedIntersectionCovariant($existing, $expected); } if ($existing instanceof IntersectionTypeNode) { - return self::checkExistingIntersectionVariance($existing, $expected, $variance); + return self::checkExistingIntersectionCovariant($existing, $expected); } $existingStr = (string) $existing; @@ -3739,10 +3762,6 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str return self::isSubclass($existingStr, $expectedStr); } - if ($variance === GenericTypeNode::VARIANCE_CONTRAVARIANT) { - return self::isSubclass($expectedStr, $existingStr); - } - return false; } @@ -3860,18 +3879,8 @@ private static function isScalarSubtype(string $sub, string $super): bool return false; } - private static function checkExpectedUnionVariance(TypeNode $existing, UnionTypeNode $expected, string $variance): bool + private static function checkExpectedUnionCovariant(TypeNode $existing, UnionTypeNode $expected): bool { - if ($variance === GenericTypeNode::VARIANCE_CONTRAVARIANT) { - foreach ($expected->types as $unionVariant) { - if (! self::checkVariance($existing, $unionVariant, $variance)) { - return false; - } - } - - return true; - } - if ($existing instanceof IdentifierTypeNode) { self::$compiledUnionMembersCache ??= new WeakMap(); $compiled = self::$compiledUnionMembersCache[$expected] ?? null; @@ -3905,7 +3914,7 @@ private static function checkExpectedUnionVariance(TypeNode $existing, UnionType if ($existing instanceof UnionTypeNode) { foreach ($existing->types as $existingVariant) { - if (! self::checkExpectedUnionVariance($existingVariant, $expected, $variance)) { + if (! self::checkExpectedUnionCovariant($existingVariant, $expected)) { return false; } } @@ -3922,43 +3931,19 @@ private static function checkExpectedUnionVariance(TypeNode $existing, UnionType return false; } - private static function checkExistingUnionVariance(UnionTypeNode $existing, TypeNode $expected, string $variance): bool + private static function checkExistingUnionCovariant(UnionTypeNode $existing, TypeNode $expected): bool { - if ($variance === GenericTypeNode::VARIANCE_COVARIANT) { - foreach ($existing->types as $existingVariant) { - if (! self::checkVariance($existingVariant, $expected, $variance)) { - return false; - } - } - - return true; - } - - if ($variance === GenericTypeNode::VARIANCE_CONTRAVARIANT) { - foreach ($existing->types as $existingVariant) { - if (self::checkVariance($existingVariant, $expected, $variance)) { - return true; - } + foreach ($existing->types as $existingVariant) { + if (! self::checkVariance($existingVariant, $expected, GenericTypeNode::VARIANCE_COVARIANT)) { + return false; } - - return false; } - return false; + return true; } - private static function checkExpectedIntersectionVariance(TypeNode $existing, IntersectionTypeNode $expected, string $variance): bool + private static function checkExpectedIntersectionCovariant(TypeNode $existing, IntersectionTypeNode $expected): bool { - if ($variance === GenericTypeNode::VARIANCE_CONTRAVARIANT) { - foreach ($expected->types as $intersectionMember) { - if (! self::checkVariance($existing, $intersectionMember, $variance)) { - return false; - } - } - - return true; - } - foreach ($expected->types as $intersectionMember) { if (! self::checkVariance($existing, $intersectionMember, GenericTypeNode::VARIANCE_COVARIANT)) { return false; @@ -3968,18 +3953,8 @@ private static function checkExpectedIntersectionVariance(TypeNode $existing, In return true; } - private static function checkExistingIntersectionVariance(IntersectionTypeNode $existing, TypeNode $expected, string $variance): bool + private static function checkExistingIntersectionCovariant(IntersectionTypeNode $existing, TypeNode $expected): bool { - if ($variance === GenericTypeNode::VARIANCE_CONTRAVARIANT) { - foreach ($existing->types as $existingMember) { - if (! self::checkVariance($existingMember, $expected, $variance)) { - return false; - } - } - - return true; - } - foreach ($existing->types as $existingMember) { if (self::checkVariance($existingMember, $expected, GenericTypeNode::VARIANCE_COVARIANT)) { return true; diff --git a/tests/TypeChecking/Generics/ContraVarianceSoundnessTest.php b/tests/TypeChecking/Generics/ContraVarianceSoundnessTest.php new file mode 100644 index 00000000..8fc1137f --- /dev/null +++ b/tests/TypeChecking/Generics/ContraVarianceSoundnessTest.php @@ -0,0 +1,171 @@ + $consumer + */ +function acceptContravariantPositiveIntConsumer(VarianceContravariantConsumer $consumer): void +{ +} + +/** + * @param VarianceContravariantConsumer $consumer + */ +function acceptContravariantIntConsumer(VarianceContravariantConsumer $consumer): void +{ +} + +/** + * @param VarianceContravariantConsumer $consumer + */ +function acceptContravariantDogConsumer(VarianceContravariantConsumer $consumer): void +{ +} + +/** + * @param VarianceContravariantConsumer $consumer + */ +function acceptContravariantObjectConsumer(VarianceContravariantConsumer $consumer): void +{ +} + +/** + * @param VarianceContravariantConsumer $consumer + */ +function acceptContravariantIntersectionConsumer(VarianceContravariantConsumer $consumer): void +{ +} + +/** + * @param VarianceContravariantConsumer $consumer + */ +function acceptContravariantIfaceAConsumer(VarianceContravariantConsumer $consumer): void +{ +} + +describe('Generic Contravariance Soundness', function () { + describe('Contravariant generic consumers enforce supertype direction', function () { + test('accepts Consumer for Consumer and rejects reversed Consumer for Consumer', function () { + /** @var VarianceContravariantConsumer $intConsumer */ + $intConsumer = new VarianceContravariantConsumer(); + acceptContravariantPositiveIntConsumer($intConsumer); + + /** @var VarianceContravariantConsumer $posConsumer */ + $posConsumer = new VarianceContravariantConsumer(); + + expect(fn () => acceptContravariantIntConsumer($posConsumer)) + ->toThrow(TypeError::class, 'expects VarianceContravariantConsumer') + ; + }); + + test('accepts Consumer for Consumer and rejects reversed Consumer for Consumer', function () { + /** @var VarianceContravariantConsumer $objConsumer */ + $objConsumer = new VarianceContravariantConsumer(); + acceptContravariantDogConsumer($objConsumer); + + /** @var VarianceContravariantConsumer $dogConsumer */ + $dogConsumer = new VarianceContravariantConsumer(); + + expect(fn () => acceptContravariantObjectConsumer($dogConsumer)) + ->toThrow(TypeError::class, 'expects VarianceContravariantConsumer') + ; + }); + + test('accepts Consumer for Consumer and rejects the reverse', function () { + /** @var VarianceContravariantConsumer $aConsumer */ + $aConsumer = new VarianceContravariantConsumer(); + acceptContravariantIntersectionConsumer($aConsumer); + + /** @var VarianceContravariantConsumer $abConsumer */ + $abConsumer = new VarianceContravariantConsumer(); + + expect(fn () => acceptContravariantIfaceAConsumer($abConsumer)) + ->toThrow(TypeError::class, 'expects VarianceContravariantConsumer') + ; + }); + }); + + describe('TemplateManager::checkVariance() contravariant invariants', function () { + test('handles scalars, ranges, literals, class-strings, object, collections, unions, intersections, and mixed', function () { + $int = new IdentifierTypeNode('int'); + $posInt = new IdentifierTypeNode('positive-int'); + $string = new IdentifierTypeNode('string'); + $object = new IdentifierTypeNode('object'); + $mixed = new IdentifierTypeNode('mixed'); + $array = new IdentifierTypeNode('array'); + $list = new IdentifierTypeNode('list'); + $dog = new IdentifierTypeNode(VarianceDog::class); + $intRange = new GenericTypeNode($int, [ + new ConstTypeNode(new ConstExprIntegerNode('1')), + new ConstTypeNode(new ConstExprIntegerNode('10')), + ]); + $classStringDog = new GenericTypeNode(new IdentifierTypeNode('class-string'), [$dog]); + $fooLit = new ConstTypeNode(new ConstExprStringNode('foo', ConstExprStringNode::SINGLE_QUOTED)); + $intOrString = new UnionTypeNode([$int, $string]); + $ifaceA = new IdentifierTypeNode(VarianceIfaceA::class); + $ifaceB = new IdentifierTypeNode(VarianceIfaceB::class); + $aAndB = new IntersectionTypeNode([$ifaceA, $ifaceB]); + + expect(TemplateManager::checkVariance($int, $posInt, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeTrue(); + expect(TemplateManager::checkVariance($posInt, $int, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeFalse(); + + expect(TemplateManager::checkVariance($int, $intRange, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeTrue(); + expect(TemplateManager::checkVariance($intRange, $int, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeFalse(); + + expect(TemplateManager::checkVariance($string, $fooLit, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeTrue(); + expect(TemplateManager::checkVariance($fooLit, $string, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeFalse(); + + expect(TemplateManager::checkVariance($string, $classStringDog, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeTrue(); + expect(TemplateManager::checkVariance($classStringDog, $string, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeFalse(); + + expect(TemplateManager::checkVariance($object, $dog, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeTrue(); + expect(TemplateManager::checkVariance($dog, $object, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeFalse(); + + expect(TemplateManager::checkVariance($array, $list, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeTrue(); + expect(TemplateManager::checkVariance($list, $array, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeFalse(); + + expect(TemplateManager::checkVariance($ifaceA, $aAndB, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeTrue(); + expect(TemplateManager::checkVariance($aAndB, $ifaceA, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeFalse(); + + expect(TemplateManager::checkVariance($intOrString, $int, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeTrue(); + expect(TemplateManager::checkVariance($int, $intOrString, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeFalse(); + + expect(TemplateManager::checkVariance($mixed, $int, GenericTypeNode::VARIANCE_CONTRAVARIANT))->toBeTrue(); + }); + }); +}); From b7824ea62ee501e2afaa1f55fad85bb10f2d873e Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Fri, 4 Dec 2026 23:55:20 +0800 Subject: [PATCH 07/24] Refactor ArrayLiteralEvaluator for key soundness; add comprehensive tests for numeric string key coercion and auto-index behavior --- .../Evaluator/ArrayLiteralEvaluator.php | 143 +++++++- .../ArrayLiteralEvaluatorKeySoundnessTest.php | 346 ++++++++++++++++++ 2 files changed, 476 insertions(+), 13 deletions(-) create mode 100644 tests/Internal/Ast/Elimination/ArrayLiteralEvaluatorKeySoundnessTest.php diff --git a/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php index 5a443c26..8fb63a10 100644 --- a/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php +++ b/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php @@ -4,9 +4,12 @@ namespace TypePHP\Internal\Ast\Elimination\Evaluator; +use PhpParser\Node\Expr; use PhpParser\Node\Expr\Array_; use PhpParser\Node\Expr\BinaryOp\Concat; +use PhpParser\Node\Expr\UnaryMinus; use PhpParser\Node\Scalar\Encapsed; +use PhpParser\Node\Scalar\EncapsedStringPart; use PhpParser\Node\Scalar\LNumber; use PhpParser\Node\Scalar\String_; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode; @@ -226,20 +229,54 @@ private static function satisfiesKeyValueArray( return false; } - $currentIdx = 0; + /** @var int|null $currentIdx */ + $currentIdx = null; + $nextIdxOverflowed = false; foreach ($arrayExpr->items as $item) { if ($item === null || $item->unpack) { return false; } + $mayCoerceToInt = false; + if ($item->key === null) { - $keyExpr = new LNumber($currentIdx); - $currentIdx++; - } elseif ($item->key instanceof LNumber) { + if ($nextIdxOverflowed) { + return false; + } + $assignedIdx = $currentIdx ?? 0; + $keyExpr = new LNumber($assignedIdx); + if ($assignedIdx === PHP_INT_MAX) { + $nextIdxOverflowed = true; + } else { + $currentIdx = $assignedIdx + 1; + } + } elseif (($intKey = self::extractStaticIntKey($item->key)) !== null) { $keyExpr = $item->key; - $currentIdx = max($currentIdx, $item->key->value + 1); - } elseif ($item->key instanceof String_ || $item->key instanceof Concat || $item->key instanceof Encapsed) { + if ($currentIdx === null || $intKey >= $currentIdx) { + if ($intKey === PHP_INT_MAX) { + $nextIdxOverflowed = true; + } else { + $currentIdx = $intKey + 1; + } + } + } elseif ($item->key instanceof String_) { + $rawKey = $item->key->value; + if ($rawKey !== '' && (string) (int) $rawKey === $rawKey) { + $coercedInt = (int) $rawKey; + $keyExpr = new LNumber($coercedInt); + if ($currentIdx === null || $coercedInt >= $currentIdx) { + if ($coercedInt === PHP_INT_MAX) { + $nextIdxOverflowed = true; + } else { + $currentIdx = $coercedInt + 1; + } + } + } else { + $keyExpr = $item->key; + } + } elseif ($item->key instanceof Concat || $item->key instanceof Encapsed) { $keyExpr = $item->key; + $mayCoerceToInt = ! self::isGuaranteedNonNumericStringExpr($item->key); } else { return false; } @@ -248,6 +285,16 @@ private static function satisfiesKeyValueArray( return false; } + if ($mayCoerceToInt) { + if ( + ! StaticTypeEvaluator::satisfies(new LNumber(0), $keyType, $currentFile, $trustedVariableTypes, $currentNamespace) + || ! StaticTypeEvaluator::satisfies(new LNumber(1), $keyType, $currentFile, $trustedVariableTypes, $currentNamespace) + || ! StaticTypeEvaluator::satisfies(new UnaryMinus(new LNumber(1)), $keyType, $currentFile, $trustedVariableTypes, $currentNamespace) + ) { + return false; + } + } + if (! StaticTypeEvaluator::satisfies($item->value, $valueType, $currentFile, $trustedVariableTypes, $currentNamespace)) { return false; } @@ -289,20 +336,47 @@ private static function satisfiesArrayShape( } $actualItems = []; - $currentIdx = 0; + /** @var int|null $currentIdx */ + $currentIdx = null; + $nextIdxOverflowed = false; foreach ($arrayExpr->items as $item) { if ($item === null || $item->unpack) { return false; } if ($item->key === null) { - $key = $currentIdx; - $currentIdx++; - } elseif ($item->key instanceof LNumber) { - $key = $item->key->value; - $currentIdx = max($currentIdx, $key + 1); + if ($nextIdxOverflowed) { + return false; + } + $key = $currentIdx ?? 0; + if ($key === PHP_INT_MAX) { + $nextIdxOverflowed = true; + } else { + $currentIdx = $key + 1; + } + } elseif (($intKey = self::extractStaticIntKey($item->key)) !== null) { + $key = $intKey; + if ($currentIdx === null || $key >= $currentIdx) { + if ($key === PHP_INT_MAX) { + $nextIdxOverflowed = true; + } else { + $currentIdx = $key + 1; + } + } } elseif ($item->key instanceof String_) { - $key = $item->key->value; + $rawKey = $item->key->value; + if ($rawKey !== '' && (string) (int) $rawKey === $rawKey) { + $key = (int) $rawKey; + if ($currentIdx === null || $key >= $currentIdx) { + if ($key === PHP_INT_MAX) { + $nextIdxOverflowed = true; + } else { + $currentIdx = $key + 1; + } + } + } else { + $key = $rawKey; + } } else { return false; } @@ -350,6 +424,49 @@ private static function satisfiesArrayShape( return true; } + /** + * Evaluates a static integer array key expression (e.g. 5, -5, 1 + 2), returning null for floats or dynamic expressions. + */ + private static function extractStaticIntKey(Expr $expr): ?int + { + if ($expr instanceof LNumber) { + return $expr->value; + } + + $folded = ArithmeticEvaluator::evaluate($expr); + + return \is_int($folded) ? $folded : null; + } + + /** + * Checks whether a string concatenation or interpolation contains a static fragment that + * guarantees the resulting key can never coerce into a PHP canonical integer key. + */ + private static function isGuaranteedNonNumericStringExpr(Expr $expr): bool + { + if ($expr instanceof String_) { + return preg_match('/[^0-9\-]|[\s\S]-/', $expr->value) === 1; + } + + if ($expr instanceof Concat) { + return self::isGuaranteedNonNumericStringExpr($expr->left) + || self::isGuaranteedNonNumericStringExpr($expr->right); + } + + if ($expr instanceof Encapsed) { + foreach ($expr->parts as $part) { + if ($part instanceof EncapsedStringPart && preg_match('/[^0-9\-]|[\s\S]-/', $part->value) === 1) { + return true; + } + if ($part instanceof String_ && preg_match('/[^0-9\-]|[\s\S]-/', $part->value) === 1) { + return true; + } + } + } + + return false; + } + /** * Checks whether an array expression has sequential 0..n-1 integer keys. */ diff --git a/tests/Internal/Ast/Elimination/ArrayLiteralEvaluatorKeySoundnessTest.php b/tests/Internal/Ast/Elimination/ArrayLiteralEvaluatorKeySoundnessTest.php new file mode 100644 index 00000000..c05d3429 --- /dev/null +++ b/tests/Internal/Ast/Elimination/ArrayLiteralEvaluatorKeySoundnessTest.php @@ -0,0 +1,346 @@ + + */ +function elimNumericStringKeyToStringMap(): array +{ + return ['123' => 'hello']; +} + +/** + * @return array + */ +function elimZeroStringKeyToStringMap(): array +{ + return ['0' => 'zero']; +} + +/** + * @return array + */ +function elimDynamicNumericConcatKey(string $suffix): array +{ + return ['1' . $suffix => 'val']; +} + +/** + * @return array + */ +function elimDynamicNumericInterpolatedKey(string $suffix): array +{ + return ["1{$suffix}" => 'val']; +} + +/** + * @return array<0|5, string> + */ +function elimStringIntKeyShiftsAutoKey(): array +{ + return ['5' => 'five', 'six']; +} + +/** + * @return array{'5': string, 0: int} + */ +function elimShapeStringKeyAutoIndexMismatch(): array +{ + return ['5' => 'five', 99]; +} + +/** + * @return array{-5: string, 0: int} + */ +function elimShapeNegativeKeyAutoIndexMismatch(): array +{ + return [-5 => 'neg', 99]; +} + +/** + * @return array + */ +function elimValidNonCanonicalStringKeys(): array +{ + return [ + '01' => 'leading-zero', + '-0' => 'neg-zero', + '+1' => 'plus-one', + '1.0' => 'dot-zero', + ' 1' => 'leading-space', + '9223372036854775808' => 'overflow', + ]; +} + +/** + * @return array + */ +function elimValidNonNumericInterpolatedKey(int $id): array +{ + return ["user_{$id}" => 'ok']; +} + +describe('ArrayLiteralEvaluator Key Coercion & Auto-Index Soundness', function () { + beforeEach(function () { + Config::set(['eliminate_statically_proven_checks' => true]); + }); + + afterEach(function () { + Config::reset(); + }); + + describe('Numeric string key coercion in array', function () { + test('does not satisfy array for canonical numeric string keys', function () { + $stringMap = new GenericTypeNode(new IdentifierTypeNode('array'), [ + new IdentifierTypeNode('string'), + new IdentifierTypeNode('string'), + ]); + $nonEmptyStringMap = new GenericTypeNode(new IdentifierTypeNode('array'), [ + new IdentifierTypeNode('non-empty-string'), + new IdentifierTypeNode('string'), + ]); + + foreach (['0', '1', '-1', '123', '-42', (string) PHP_INT_MAX, (string) PHP_INT_MIN] as $numStr) { + $arr = new Array_([new ArrayItem(new String_('val'), new String_($numStr))]); + + expect(StaticTypeEvaluator::satisfies($arr, $stringMap))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($arr, $nonEmptyStringMap))->toBeFalse(); + } + }); + + test('throws TypeError at runtime instead of eliminating numeric string keys in array', function () { + expect(fn () => elimNumericStringKeyToStringMap()) + ->toThrow(TypeError::class, 'key must be of type string') + ; + + expect(fn () => elimZeroStringKeyToStringMap()) + ->toThrow(TypeError::class, 'key must be of type string') + ; + }); + + test('evaluates canonical numeric string keys as int against constrained int key types', function () { + $posIntMap = new GenericTypeNode(new IdentifierTypeNode('array'), [ + new IdentifierTypeNode('positive-int'), + new IdentifierTypeNode('string'), + ]); + $intMap = new GenericTypeNode(new IdentifierTypeNode('array'), [ + new IdentifierTypeNode('int'), + new IdentifierTypeNode('string'), + ]); + + $negArr = new Array_([new ArrayItem(new String_('val'), new String_('-5'))]); + $posArr = new Array_([new ArrayItem(new String_('val'), new String_('5'))]); + + expect(StaticTypeEvaluator::satisfies($negArr, $posIntMap))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($negArr, $intMap))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies($posArr, $posIntMap))->toBeTrue(); + }); + + test('still eliminates non-canonical numeric strings for array', function () { + expect(elimValidNonCanonicalStringKeys())->toBe([ + '01' => 'leading-zero', + '-0' => 'neg-zero', + '+1' => 'plus-one', + '1.0' => 'dot-zero', + ' 1' => 'leading-space', + '9223372036854775808' => 'overflow', + ]); + + $transformed = StreamWrapper::transformSource((string) file_get_contents(__FILE__), __FILE__); + preg_match('/function elimValidNonCanonicalStringKeys\b.*?\{(.*?)\}/s', $transformed, $matches); + expect($matches[1] ?? '')->not->toContain('checkReturn'); + }); + }); + + describe('Dynamic Concat and Encapsed key coercion risk', function () { + test('does not eliminate Concat or Encapsed keys that may coerce to integer keys against string/non-empty-string', function () { + $stringMap = new GenericTypeNode(new IdentifierTypeNode('array'), [ + new IdentifierTypeNode('string'), + new IdentifierTypeNode('string'), + ]); + $nonEmptyStringMap = new GenericTypeNode(new IdentifierTypeNode('array'), [ + new IdentifierTypeNode('non-empty-string'), + new IdentifierTypeNode('string'), + ]); + $arrayKeyMap = new GenericTypeNode(new IdentifierTypeNode('array'), [ + new IdentifierTypeNode('array-key'), + new IdentifierTypeNode('string'), + ]); + + $concatKey = new Concat(new String_('1'), new Variable('suffix')); + $encapsedKey = new Encapsed([new EncapsedStringPart('1'), new Variable('suffix')]); + + $arrConcat = new Array_([new ArrayItem(new String_('val'), $concatKey)]); + $arrEncapsed = new Array_([new ArrayItem(new String_('val'), $encapsedKey)]); + + expect(StaticTypeEvaluator::satisfies($arrConcat, $stringMap))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($arrConcat, $nonEmptyStringMap))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($arrEncapsed, $stringMap))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($arrEncapsed, $nonEmptyStringMap))->toBeFalse(); + + expect(StaticTypeEvaluator::satisfies($arrConcat, $arrayKeyMap))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies($arrEncapsed, $arrayKeyMap))->toBeTrue(); + }); + + test('throws TypeError at runtime when dynamic Concat or Encapsed key coerces to int', function () { + expect(fn () => elimDynamicNumericConcatKey('23')) + ->toThrow(TypeError::class, 'key must be of type string') + ; + + expect(fn () => elimDynamicNumericInterpolatedKey('')) + ->toThrow(TypeError::class, 'key must be of type non-empty-string') + ; + }); + + test('still eliminates Concat and Encapsed keys guaranteed non-numeric by static chunks', function () { + expect(elimValidNonNumericInterpolatedKey(7))->toBe(['user_7' => 'ok']); + + $transformed = StreamWrapper::transformSource((string) file_get_contents(__FILE__), __FILE__); + preg_match('/function elimValidNonNumericInterpolatedKey\b.*?\{(.*?)\}/s', $transformed, $matches); + expect($matches[1] ?? '')->not->toContain('checkReturn'); + }); + }); + + describe('Auto-increment index synchronization after numeric string and negative keys', function () { + test('advances auto-key index after numeric string keys in array and shapes', function () { + $union0Or5Map = new GenericTypeNode(new IdentifierTypeNode('array'), [ + new UnionTypeNode([ + new ConstTypeNode(new ConstExprIntegerNode('0')), + new ConstTypeNode(new ConstExprIntegerNode('5')), + ]), + new IdentifierTypeNode('string'), + ]); + $union5Or6Map = new GenericTypeNode(new IdentifierTypeNode('array'), [ + new UnionTypeNode([ + new ConstTypeNode(new ConstExprIntegerNode('5')), + new ConstTypeNode(new ConstExprIntegerNode('6')), + ]), + new IdentifierTypeNode('string'), + ]); + + $arr = new Array_([ + new ArrayItem(new String_('five'), new String_('5')), + new ArrayItem(new String_('six')), + ]); + + expect(StaticTypeEvaluator::satisfies($arr, $union0Or5Map))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($arr, $union5Or6Map))->toBeTrue(); + + expect(fn () => elimStringIntKeyShiftsAutoKey()) + ->toThrow(TypeError::class, 'key') + ; + }); + + test('handles negative integer keys using PHP 8+ auto-index rules in shapes and maps', function () { + $shapeMinus5AndMinus4 = ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new ConstExprIntegerNode('-5'), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new ConstExprIntegerNode('-4'), false, new IdentifierTypeNode('int')), + ]); + $shapeMinus5And0 = ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new ConstExprIntegerNode('-5'), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new ConstExprIntegerNode('0'), false, new IdentifierTypeNode('int')), + ]); + + $negLitArr = new Array_([ + new ArrayItem(new String_('neg'), new UnaryMinus(new LNumber(5))), + new ArrayItem(new LNumber(99)), + ]); + $negStrArr = new Array_([ + new ArrayItem(new String_('neg'), new String_('-5')), + new ArrayItem(new LNumber(99)), + ]); + $strThenNegArr = new Array_([ + new ArrayItem(new String_('x'), new String_('foo')), + new ArrayItem(new String_('neg'), new UnaryMinus(new LNumber(5))), + new ArrayItem(new LNumber(99)), + ]); + + $shapeFooMinus5Minus4 = ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new ConstExprStringNode('foo', ConstExprStringNode::SINGLE_QUOTED), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new ConstExprIntegerNode('-5'), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new ConstExprIntegerNode('-4'), false, new IdentifierTypeNode('int')), + ]); + $shapeFooMinus5And0 = ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new ConstExprStringNode('foo', ConstExprStringNode::SINGLE_QUOTED), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new ConstExprIntegerNode('-5'), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new ConstExprIntegerNode('0'), false, new IdentifierTypeNode('int')), + ]); + + expect(StaticTypeEvaluator::satisfies($negLitArr, $shapeMinus5AndMinus4))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies($negStrArr, $shapeMinus5AndMinus4))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies($negLitArr, $shapeMinus5And0))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($negStrArr, $shapeMinus5And0))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($strThenNegArr, $shapeFooMinus5Minus4))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies($strThenNegArr, $shapeFooMinus5And0))->toBeFalse(); + + expect(fn () => elimShapeStringKeyAutoIndexMismatch()) + ->toThrow(TypeError::class) + ; + + expect(fn () => elimShapeNegativeKeyAutoIndexMismatch()) + ->toThrow(TypeError::class) + ; + }); + + test('matches PHP auto-key after explicit positive then negative keys ([2 => a, -5 => b, c] => key 3)', function () { + $shapeValid = ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new ConstExprIntegerNode('2'), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new ConstExprIntegerNode('-5'), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new ConstExprIntegerNode('3'), false, new IdentifierTypeNode('string')), + ]); + $shapeWrong = ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new ConstExprIntegerNode('2'), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new ConstExprIntegerNode('-5'), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new ConstExprIntegerNode('-4'), false, new IdentifierTypeNode('string')), + ]); + + $arr = new Array_([ + new ArrayItem(new String_('a'), new LNumber(2)), + new ArrayItem(new String_('b'), new UnaryMinus(new LNumber(5))), + new ArrayItem(new String_('c')), + ]); + + expect(StaticTypeEvaluator::satisfies($arr, $shapeValid))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies($arr, $shapeWrong))->toBeFalse(); + + $shape5And6 = ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new ConstExprIntegerNode('5'), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new ConstExprIntegerNode('6'), false, new IdentifierTypeNode('int')), + ]); + $shape5And0 = ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new ConstExprStringNode('5', ConstExprStringNode::SINGLE_QUOTED), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new ConstExprIntegerNode('0'), false, new IdentifierTypeNode('int')), + ]); + + $str5Arr = new Array_([ + new ArrayItem(new String_('five'), new String_('5')), + new ArrayItem(new LNumber(99)), + ]); + + expect(StaticTypeEvaluator::satisfies($str5Arr, $shape5And0))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($str5Arr, $shape5And6))->toBeTrue(); + }); + }); +}); From 4fd9502cbde2b53a229e05c8a591146d09682ba6 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sat, 5 Dec 2026 00:22:58 +0800 Subject: [PATCH 08/24] Enhance ConstantAndEnumEvaluator with non-autoloading checks for constants; add IntMaskOfConstantSoundnessTest for comprehensive validation of int-mask behavior --- .../Evaluator/ConstantAndEnumEvaluator.php | 62 ++++- .../IntMaskOfConstantSoundnessTest.php | 236 ++++++++++++++++++ 2 files changed, 293 insertions(+), 5 deletions(-) create mode 100644 tests/Internal/Ast/Elimination/IntMaskOfConstantSoundnessTest.php diff --git a/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php index 7fbe3321..fa8d96cd 100644 --- a/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php +++ b/src/Internal/Ast/Elimination/Evaluator/ConstantAndEnumEvaluator.php @@ -16,7 +16,9 @@ use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; +use ReflectionClass; use TypePHP\Internal\Ast\Elimination\StaticTypeEvaluator; +use TypePHP\Internal\Diagnostic\DebugLog; use UnitEnum; /** @@ -122,6 +124,18 @@ private static function satisfiesClassConst( return false; } + $isSyntheticSelf = $currentFile === '' + && ! $targetClassNode->isFullyQualified() + && ! $targetClassNode->isRelative() + && strtolower($targetClassNode->toString()) === 'self'; + + if (! $isSyntheticSelf) { + $resolvedClass = self::resolveClassForReflection($targetClassNode, $currentFile, $currentNamespace); + if (! self::isLoadedIntConstant($resolvedClass, $constName)) { + return false; + } + } + $pattern = $inner->constExpr->name; if (str_contains($pattern, '*')) { return self::matchesWildcard($constName, $pattern); @@ -235,10 +249,10 @@ private static function resolveClassForReflection(Name $classNode, string $curre if ( ! $classNode->isFullyQualified() && ! $classNode->isRelative() - && ! enum_exists($resolved, false) + && ! self::isLoadedSymbol($resolved) ) { $raw = $classNode->toString(); - if (str_contains($raw, '\\') && enum_exists($raw, false)) { + if (str_contains($raw, '\\') && self::isLoadedSymbol($raw)) { return $raw; } } @@ -246,6 +260,44 @@ private static function resolveClassForReflection(Name $classNode, string $curre return $resolved; } + /** + * Checks whether a class, interface, or enum is already loaded without triggering autoloading. + */ + private static function isLoadedSymbol(string $symbol): bool + { + return $symbol !== '' && ( + class_exists($symbol, false) + || interface_exists($symbol, false) + || enum_exists($symbol, false) + ); + } + + /** + * Verifies via non-autoloading reflection that a constant exists, is not an enum case, + * and evaluates to a concrete integer. + */ + private static function isLoadedIntConstant(string $resolvedClass, string $constName): bool + { + if (! self::isLoadedSymbol($resolvedClass)) { + return false; + } + + try { + /** @var class-string $resolvedClass */ + $refClass = new ReflectionClass($resolvedClass); + $refConst = $refClass->getReflectionConstant($constName); + if ($refConst === false || $refConst->isEnumCase()) { + return false; + } + + return \is_int($refConst->getValue()); + } catch (\Throwable $e) { + DebugLog::swallowed($e); // @codeCoverageIgnore + + return false; + } + } + /** * Verifies that a symbol is a declared enum case (excluding regular class constants on enums). */ @@ -265,12 +317,12 @@ private static function isEnumCase(string $enumClass, string $caseName): bool } /** - * Compares a constant name against a wildcard pattern prefix (e.g. 'STATUS_PAID' vs 'STATUS_*'). + * Compares a constant name against a wildcard pattern (e.g. 'STATUS_PAID' vs 'STATUS_*'). */ private static function matchesWildcard(string $actualName, string $pattern): bool { - $prefix = rtrim($pattern, '*'); + $regex = '/^' . str_replace('\*', '.*', preg_quote($pattern, '/')) . '$/i'; - return str_starts_with(strtoupper($actualName), strtoupper($prefix)); + return preg_match($regex, $actualName) === 1; } } diff --git a/tests/Internal/Ast/Elimination/IntMaskOfConstantSoundnessTest.php b/tests/Internal/Ast/Elimination/IntMaskOfConstantSoundnessTest.php new file mode 100644 index 00000000..fde66673 --- /dev/null +++ b/tests/Internal/Ast/Elimination/IntMaskOfConstantSoundnessTest.php @@ -0,0 +1,236 @@ + + */ +function returnStringFlagInIntMask(): mixed +{ + return IntMaskFlagsFixture::FLAG_LABEL; +} + +/** + * @return int-mask-of + */ +function returnFloatFlagInIntMask(): mixed +{ + return IntMaskFlagsFixture::FLAG_FLOAT; +} + +/** + * @return int-mask-of + */ +function returnBoolFlagInIntMask(): mixed +{ + return IntMaskFlagsFixture::FLAG_BOOL; +} + +/** + * @return int-mask-of + */ +function returnArrayFlagInIntMask(): mixed +{ + return IntMaskFlagsFixture::FLAG_ARRAY; +} + +/** + * @return int-mask-of + */ +function returnBitwiseOrWithStringFlag(): mixed +{ + return IntMaskFlagsFixture::FLAG_STR_NUM_A | IntMaskFlagsFixture::FLAG_STR_NUM_B; +} + +/** + * @return int-mask-of + */ +function returnBitwiseOrWithFloatFlag(): int +{ + return IntMaskFlagsFixture::FLAG_FLOAT_OUT | IntMaskFlagsFixture::FLAG_READ; +} + +final class SelfMaskFlagsFixture +{ + public const FLAG_READ = 1; + public const FLAG_LABEL = 'read'; + + /** + * @return int-mask-of + */ + public function returnSelfNonIntFlag(): mixed + { + return self::FLAG_LABEL; + } +} + +/** + * @return int-mask-of + */ +function returnExactStringFlagInIntMask(): mixed +{ + return IntMaskFlagsFixture::FLAG_LABEL; +} + +/** + * @return int-mask-of + */ +function returnBackedEnumCaseInIntMask(): mixed +{ + return IntMaskBackedEnumFixture::FLAG_CASE; +} + +/** + * @return int-mask-of + */ +function returnValidIntFlagsMask(): int +{ + return IntMaskFlagsFixture::FLAG_READ | IntMaskFlagsFixture::FLAG_WRITE; +} + +describe('ConstantAndEnumEvaluator int-mask-of Soundness', function () { + beforeEach(function () { + Config::set(['eliminate_statically_proven_checks' => true]); + }); + + afterEach(function () { + Config::reset(); + }); + + test('does not satisfy int-mask-of when matching constant is string, float, bool, array, or null', function () { + $maskWildcard = new GenericTypeNode(new IdentifierTypeNode('int-mask-of'), [ + new ConstTypeNode(new ConstFetchNode(IntMaskFlagsFixture::class, 'FLAG_*')), + ]); + $maskExactNonInt = new GenericTypeNode(new IdentifierTypeNode('int-mask-of'), [ + new ConstTypeNode(new ConstFetchNode(IntMaskFlagsFixture::class, 'FLAG_LABEL')), + ]); + + foreach (['FLAG_LABEL', 'FLAG_FLOAT', 'FLAG_BOOL', 'FLAG_ARRAY', 'FLAG_NULL'] as $constName) { + $fetch = new ClassConstFetch(new Name(IntMaskFlagsFixture::class), new Identifier($constName)); + expect(StaticTypeEvaluator::satisfies($fetch, $maskWildcard, __FILE__))->toBeFalse(); + } + + $labelFetch = new ClassConstFetch(new Name(IntMaskFlagsFixture::class), new Identifier('FLAG_LABEL')); + expect(StaticTypeEvaluator::satisfies($labelFetch, $maskExactNonInt, __FILE__))->toBeFalse(); + }); + + test('does not satisfy int-mask-of when BitwiseOr includes a non-int constant', function () { + $maskWildcard = new GenericTypeNode(new IdentifierTypeNode('int-mask-of'), [ + new ConstTypeNode(new ConstFetchNode(IntMaskFlagsFixture::class, 'FLAG_*')), + ]); + + $intFetch = new ClassConstFetch(new Name(IntMaskFlagsFixture::class), new Identifier('FLAG_READ')); + $strFetch = new ClassConstFetch(new Name(IntMaskFlagsFixture::class), new Identifier('FLAG_LABEL')); + $floatFetch = new ClassConstFetch(new Name(IntMaskFlagsFixture::class), new Identifier('FLAG_FLOAT')); + + expect(StaticTypeEvaluator::satisfies(new BitwiseOr($intFetch, $strFetch), $maskWildcard, __FILE__))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies(new BitwiseOr($intFetch, $floatFetch), $maskWildcard, __FILE__))->toBeFalse(); + }); + + test('does not satisfy int-mask-of when matching symbol is an enum case object', function () { + $maskEnumWildcard = new GenericTypeNode(new IdentifierTypeNode('int-mask-of'), [ + new ConstTypeNode(new ConstFetchNode(IntMaskBackedEnumFixture::class, 'FLAG_*')), + ]); + + $enumFetch = new ClassConstFetch(new Name(IntMaskBackedEnumFixture::class), new Identifier('FLAG_CASE')); + + expect(StaticTypeEvaluator::satisfies($enumFetch, $maskEnumWildcard, __FILE__))->toBeFalse(); + }); + + test('does not satisfy int-mask-of for unloaded external classes', function () { + $unloadedClass = 'NonExistentUnloadedFlags_' . bin2hex(random_bytes(4)); + $mask = new GenericTypeNode(new IdentifierTypeNode('int-mask-of'), [ + new ConstTypeNode(new ConstFetchNode('\\' . $unloadedClass, 'FLAG_*')), + ]); + $fetch = new ClassConstFetch(new FullyQualified($unloadedClass), new Identifier('FLAG_A')); + + expect(StaticTypeEvaluator::satisfies($fetch, $mask, __FILE__))->toBeFalse(); + }); + + test('retains checkReturn and throws TypeError at runtime for non-int constants matching int-mask-of', function () { + expect(fn () => returnStringFlagInIntMask()) + ->toThrow(TypeError::class, 'must be of type int (bitmask)') + ; + + expect(fn () => returnFloatFlagInIntMask()) + ->toThrow(TypeError::class, 'must be of type int (bitmask)') + ; + + expect(fn () => returnBoolFlagInIntMask()) + ->toThrow(TypeError::class, 'must be of type int (bitmask)') + ; + + expect(fn () => returnArrayFlagInIntMask()) + ->toThrow(TypeError::class, 'must be of type int (bitmask)') + ; + + expect(fn () => returnBitwiseOrWithStringFlag()) + ->toThrow(TypeError::class, 'must be of type int (bitmask)') + ; + + expect(fn () => returnBitwiseOrWithFloatFlag()) + ->toThrow(TypeError::class, 'must be a valid bitmask combination') + ; + + expect(fn () => (new SelfMaskFlagsFixture())->returnSelfNonIntFlag()) + ->toThrow(TypeError::class, 'must be of type int (bitmask)') + ; + + expect(fn () => returnExactStringFlagInIntMask()) + ->toThrow(TypeError::class, 'must be of type int (bitmask)') + ; + + expect(fn () => returnBackedEnumCaseInIntMask()) + ->toThrow(TypeError::class, 'must be of type int (bitmask)') + ; + }); + + test('still eliminates int-mask-of checks for genuine loaded integer constants and bitwise ORs', function () { + $maskWildcard = new GenericTypeNode(new IdentifierTypeNode('int-mask-of'), [ + new ConstTypeNode(new ConstFetchNode(IntMaskFlagsFixture::class, 'FLAG_*')), + ]); + + $readFetch = new ClassConstFetch(new Name(IntMaskFlagsFixture::class), new Identifier('FLAG_READ')); + $writeFetch = new ClassConstFetch(new Name(IntMaskFlagsFixture::class), new Identifier('FLAG_WRITE')); + + expect(StaticTypeEvaluator::satisfies($readFetch, $maskWildcard, __FILE__))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies(new BitwiseOr($readFetch, $writeFetch), $maskWildcard, __FILE__))->toBeTrue(); + expect(returnValidIntFlagsMask())->toBe(3); + + $transformed = StreamWrapper::transformSource((string) file_get_contents(__FILE__), __FILE__); + preg_match('/function returnValidIntFlagsMask\b.*?\{(.*?)\}/s', $transformed, $matches); + expect($matches[1] ?? '')->not->toContain('checkReturn'); + }); +}); From dbcfa05ce3fd9a40ebf96bc13757340e3530b070 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sat, 5 Dec 2026 00:42:09 +0800 Subject: [PATCH 09/24] Add by-reference return tests for single evaluation and aliasing soundness --- src/Internal/Ast/FunctionContractInjector.php | 34 +++- .../ByRefReturnSingleEvaluationTest.php | 167 ++++++++++++++++++ 2 files changed, 198 insertions(+), 3 deletions(-) create mode 100644 tests/TypeChecking/Boundaries/ByRefReturnSingleEvaluationTest.php diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index c0676866..0af3c360 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -1111,9 +1111,37 @@ public static function isTrivialPureReturnExpr(Node\Expr $expr): bool || ($expr instanceof Node\Expr\ConstFetch && \in_array(strtolower($expr->name->toString()), ['true', 'false', 'null'], true)); } + /** + * Checks whether an expression can legally appear on the right-hand side of a reference assignment (`=&`). + */ + private static function isReferenceableExpr(Node\Expr $expr): bool + { + if ($expr instanceof Node\Expr\Variable || $expr instanceof Node\Expr\StaticPropertyFetch) { + return true; + } + + if ($expr instanceof Node\Expr\PropertyFetch) { + return $expr->var instanceof Node\Expr\New_ || self::isReferenceableExpr($expr->var); + } + + if ($expr instanceof Node\Expr\ArrayDimFetch) { + return $expr->dim !== null && self::isReferenceableExpr($expr->var); + } + + if ( + $expr instanceof Node\Expr\FuncCall + || $expr instanceof Node\Expr\MethodCall + || $expr instanceof Node\Expr\StaticCall + ) { + return ! $expr->isFirstClassCallable(); + } + + return false; + } + /** * Hoists a non-trivial return expression into a temporary variable so that it executes - * before @self-out and @param-out post-conditions are checked. + * once and before @self-out, @param-out, or by-reference return checks. * * @return list */ @@ -1125,7 +1153,7 @@ public static function hoistReturnExprForExitChecks(Node\Stmt\Return_ $returnNod } $retVar = new Node\Expr\Variable('__typephpRetVal'); - $assign = $byRef + $assign = ($byRef && self::isReferenceableExpr($originalExpr)) ? new Node\Expr\AssignRef($retVar, $originalExpr) : new Node\Expr\Assign($retVar, $originalExpr); @@ -2250,7 +2278,7 @@ public function enterNode(Node $n): int|array|null } $originalExpr = $n->expr; - $preEvalStmts = $exitStmts !== [] + $preEvalStmts = ($exitStmts !== [] || ($this->isByRefReturn && $this->hasReturn)) ? FunctionContractInjector::hoistReturnExprForExitChecks($n, $this->isByRefReturn) : []; diff --git a/tests/TypeChecking/Boundaries/ByRefReturnSingleEvaluationTest.php b/tests/TypeChecking/Boundaries/ByRefReturnSingleEvaluationTest.php new file mode 100644 index 00000000..89a7b2ce --- /dev/null +++ b/tests/TypeChecking/Boundaries/ByRefReturnSingleEvaluationTest.php @@ -0,0 +1,167 @@ + + */ + public array $slots = [0 => 10, 1 => -999]; + + public int $cursor = 0; + + private int $singleSlot = 10; + + private mixed $badSlot = -5; + + public function &acquireSlot(): int + { + $this->slotAccessCount++; + + return $this->singleSlot; + } + + public function &acquireBadSlot(): mixed + { + $this->slotAccessCount++; + + return $this->badSlot; + } + + /** + * @return positive-int + */ + public function &getPositiveSlot(): int + { + return $this->acquireSlot(); + } + + /** + * @return positive-int + */ + public function &getBadPositiveSlot(): mixed + { + return $this->acquireBadSlot(); + } + + /** + * @return positive-int + */ + public function &nextArraySlot(): mixed + { + return $this->slots[$this->cursor++]; + } + + public function getSingleSlotValue(): int + { + return $this->singleSlot; + } +} + +/** + * @param mixed $out + * + * @param-out positive-int $out + * + * @return positive-int + */ +function &byRefReturnWithParamOut(array &$backing, int &$calls, mixed &$out): int +{ + $pick = static function &() use (&$backing, &$calls, &$out): int { + $calls++; + $out = 77; + + return $backing[0]; + }; + + return $pick(); +} + +describe('By-Reference Return Guard Single Evaluation & Aliasing Soundness', function () { + test('evaluates method call in by-reference return exactly once and preserves reference aliasing', function () { + $holder = new ByRefReturnSlotHolder(); + + $ref = &$holder->getPositiveSlot(); + + expect($holder->slotAccessCount)->toBe(1); + expect($ref)->toBe(10); + + $ref = 55; + expect($holder->getSingleSlotValue())->toBe(55); + }); + + test('evaluates failing by-reference return expression once before throwing TypeError', function () { + $holder = new ByRefReturnSlotHolder(); + + expect(fn () => $holder->getBadPositiveSlot()) + ->toThrow(TypeError::class, 'Return value must be of type positive-int') + ; + + expect($holder->slotAccessCount)->toBe(1); + }); + + test('evaluates ArrayDimFetch side-effect index in by-reference return exactly once', function () { + $holder = new ByRefReturnSlotHolder(); + + // Slot 0 is 10 (valid), Slot 1 is -999 (invalid). + // Double evaluation checks Slot 0 (10, passes) and returns Slot 1 (-999)! + $ref = &$holder->nextArraySlot(); + + expect($holder->cursor)->toBe(1); + expect($ref)->toBe(10); + + $ref = 42; + expect($holder->slots[0])->toBe(42); + }); + + test('evaluates by-reference return with @param-out once and preserves aliasing', function () { + $backing = [15]; + $calls = 0; + $out = null; + + $ref = &byRefReturnWithParamOut($backing, $calls, $out); + + expect($calls)->toBe(1); + expect($out)->toBe(77); + expect($ref)->toBe(15); + + $ref = 88; + expect($backing[0])->toBe(88); + }); + + test('AST transformation handles non-referenceable expressions inside by-ref functions without syntax errors', function () { + $source = <<<'PHP' +acquireSlot(); +} +PHP; + + $transformed = StreamWrapper::transformSource($source, __FILE__); + + expect(substr_count($transformed, '$holder->acquireSlot()'))->toBe(1); + + $tokens = StreamWrapper::getParser()->parse($transformed); + expect($tokens)->not->toBeNull(); + }); +}); From 538fc582b1aa80a40c4d35f2996a2fcdf4440d41 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sat, 5 Dec 2026 01:15:09 +0800 Subject: [PATCH 10/24] Implement coalesce assignment handling in ContractVisitor; add computeInc and computeDec methods in RuntimeTypeChecker; enhance FunctionContractInjector with nullability checks; introduce tests for increment/decrement and coalesce assignment semantics. --- src/Internal/Ast/ContractVisitor.php | 70 +++- src/Internal/Ast/FunctionContractInjector.php | 76 +++- src/Internal/RuntimeTypeChecker.php | 32 ++ tests/Internal/Ast/ContractVisitorTest.php | 8 +- ...nctionContractEliminationEdgeCasesTest.php | 174 ++++++++++ .../Boundaries/AssignOpPrecedenceTest.php | 4 +- .../IncDecAndCoalesceAssignSoundnessTest.php | 328 ++++++++++++++++++ 7 files changed, 675 insertions(+), 17 deletions(-) create mode 100644 tests/Internal/Ast/Elimination/FunctionContractEliminationEdgeCasesTest.php create mode 100644 tests/TypeChecking/Boundaries/IncDecAndCoalesceAssignSoundnessTest.php diff --git a/src/Internal/Ast/ContractVisitor.php b/src/Internal/Ast/ContractVisitor.php index f1edb21c..d869aff5 100644 --- a/src/Internal/Ast/ContractVisitor.php +++ b/src/Internal/Ast/ContractVisitor.php @@ -53,7 +53,6 @@ final class ContractVisitor extends NodeVisitorAbstract Node\Expr\AssignOp\BitwiseXor::class => Node\Expr\BinaryOp\BitwiseXor::class, Node\Expr\AssignOp\ShiftLeft::class => Node\Expr\BinaryOp\ShiftLeft::class, Node\Expr\AssignOp\ShiftRight::class => Node\Expr\BinaryOp\ShiftRight::class, - Node\Expr\AssignOp\Coalesce::class => Node\Expr\BinaryOp\Coalesce::class, ]; private const BY_REF_BUILTIN_FUNCTIONS = [ @@ -2393,6 +2392,10 @@ private function handleForeachTypePropagation(Node\Stmt\Foreach_ $node): void private function handleAssignOp(Node\Expr\AssignOp $node): ?Node\Expr { + if ($node instanceof Node\Expr\AssignOp\Coalesce) { + return $this->handleCoalesceAssign($node); + } + $binaryOpClass = self::ASSIGN_OP_MAP[$node::class] ?? null; if ($binaryOpClass === null) { return null; @@ -2431,6 +2434,55 @@ private function handleAssignOp(Node\Expr\AssignOp $node): ?Node\Expr return new Node\Expr\Assign($node->var, $wrapped); } + private function handleCoalesceAssign(Node\Expr\AssignOp\Coalesce $node): ?Node\Expr + { + $isStandalone = $node->getAttribute('typephp_is_standalone') === true; + $line = $node->var->getStartLine(); + + if ($this->targetHasSideEffects($node->var)) { + $preAssignments = []; + $cleanTarget = $this->hoistImpureTarget($node->var, $preAssignments); + $wrappedRhs = $this->wrapTargetMutation(clone $cleanTarget, $node->expr, $line); + + if ($wrappedRhs === null) { + return null; + } + + $this->markWriteContext($cleanTarget); + $assign = new Node\Expr\Assign(clone $cleanTarget, $wrappedRhs); + $assign->setAttribute('typephp_wrapped', true); + $assign->setAttribute('typephp_needs_parens', true); + + $expr = $this->wrapWithPreEvaluations( + $preAssignments, + new Node\Expr\BinaryOp\Coalesce($cleanTarget, $assign) + ); + + if (! $isStandalone) { + $expr->setAttribute('typephp_needs_parens', true); + } + + return $expr; + } + + $wrappedRhs = $this->wrapTargetMutation(clone $node->var, $node->expr, $line); + if ($wrappedRhs === null) { + return null; + } + + $assign = new Node\Expr\Assign(clone $node->var, $wrappedRhs); + $assign->setAttribute('typephp_wrapped', true); + $assign->setAttribute('typephp_needs_parens', true); + + $expr = new Node\Expr\BinaryOp\Coalesce($node->var, $assign); + + if (! $isStandalone) { + $expr->setAttribute('typephp_needs_parens', true); + } + + return $expr; + } + private static function rhsNeedsParensInBinaryOp(Node\Expr $expr): bool { return $expr instanceof Node\Expr\BinaryOp @@ -2458,7 +2510,7 @@ private function handleIncDec(Node\Expr\PreInc|Node\Expr\PostInc|Node\Expr\PreDe $isInc = $node instanceof Node\Expr\PreInc || $node instanceof Node\Expr\PostInc; $isPost = $node instanceof Node\Expr\PostInc || $node instanceof Node\Expr\PostDec; $isStandalone = $node->getAttribute('typephp_is_standalone') === true; - $binaryClass = $isInc ? Node\Expr\BinaryOp\Plus::class : Node\Expr\BinaryOp\Minus::class; + $computeMethod = $isInc ? 'computeInc' : 'computeDec'; /** @var list $preAssignments */ $preAssignments = []; @@ -2473,8 +2525,11 @@ private function handleIncDec(Node\Expr\PreInc|Node\Expr\PostInc|Node\Expr\PreDe } $oldVar = new Node\Expr\Variable('__typephpOld' . $this->hoistTempCounter); - $binaryExpr = new $binaryClass(clone $oldVar, new Node\Scalar\LNumber(1)); - $wrapped = $this->wrapTargetMutation(clone $cleanTarget, $binaryExpr, $node->var->getStartLine()); + $stepExpr = new Node\Expr\FuncCall( + new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::' . $computeMethod), + [new Node\Arg(clone $oldVar)] + ); + $wrapped = $this->wrapTargetMutation(clone $cleanTarget, $stepExpr, $node->var->getStartLine()); if ($wrapped === null) { return null; @@ -2491,8 +2546,11 @@ private function handleIncDec(Node\Expr\PreInc|Node\Expr\PostInc|Node\Expr\PreDe return $expr; } - $binaryExpr = new $binaryClass(clone $cleanTarget, new Node\Scalar\LNumber(1)); - $wrapped = $this->wrapTargetMutation(clone $cleanTarget, $binaryExpr, $node->var->getStartLine()); + $stepExpr = new Node\Expr\FuncCall( + new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::' . $computeMethod), + [new Node\Arg(clone $cleanTarget)] + ); + $wrapped = $this->wrapTargetMutation(clone $cleanTarget, $stepExpr, $node->var->getStartLine()); if ($wrapped === null) { return null; diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index 0af3c360..a642f74b 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -325,6 +325,11 @@ private static function canEliminateSetupScope( } $paramTags = $phpDocNode !== null ? DocblockExtractor::getParamTags($phpDocNode) : []; + if (isset($paramTags[''])) { + return false; + } + + $strictNullability = ! Config::isRespectNativeNullabilityEnabled(); foreach ($node->params as $param) { if ($param->variadic || ! ($param->var instanceof Node\Expr\Variable) || ! \is_string($param->var->name)) { @@ -348,7 +353,13 @@ private static function canEliminateSetupScope( continue; } - if (! self::nativeParamSatisfiesDocType($param->type, $paramTag->type)) { + $docType = $pTypeNode ?? $paramTag->type; + + if ($strictNullability && self::hasNullDefault($param) && ! self::docTypeAllowsNull($docType)) { + return false; + } + + if (! self::nativeParamSatisfiesDocType($param->type, $docType)) { return false; } } @@ -356,6 +367,39 @@ private static function canEliminateSetupScope( return true; } + private static function hasNullDefault(Node\Param $param): bool + { + return $param->default instanceof Node\Expr\ConstFetch + && strtolower($param->default->name->toString()) === 'null'; + } + + private static function docTypeAllowsNull(TypeNode $type): bool + { + if ($type instanceof NullableTypeNode) { + return true; + } + + if ($type instanceof IdentifierTypeNode) { + $lower = strtolower($type->name); + + return $lower === 'null' || $lower === 'mixed'; + } + + if ($type instanceof \PHPStan\PhpDocParser\Ast\Type\ConstTypeNode) { + return $type->constExpr instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprNullNode; + } + + if ($type instanceof UnionTypeNode) { + foreach ($type->types as $member) { + if (self::docTypeAllowsNull($member)) { + return true; + } + } + } + + return false; + } + private static function nativeParamSatisfiesDocType( Node\Identifier|Node\Name|Node\ComplexType|null $nativeType, TypeNode $docType @@ -497,10 +541,8 @@ private static function collectTrustedParamTypes( continue; } - if ( - Config::isRespectNativeNullabilityEnabled() - && self::parameterAllowsNullNatively($p) - ) { + $allowsNullNatively = self::parameterAllowsNullNatively($p); + if ($allowsNullNatively && (Config::isRespectNativeNullabilityEnabled() || ! isset($paramTags[$pName]))) { continue; } @@ -2440,10 +2482,32 @@ public static function tagPrecedingAssignments(array $stmts): void && $curr->expr instanceof Node\Expr\Yield_ && $curr->expr->value instanceof Node\Expr\Variable && $curr->expr->value->name === $assignedVarName - && ($curr->expr->key === null || ! ($curr->expr->key instanceof Node\Expr\Assign)) + && ($curr->expr->key === null || ! self::exprMayMutateVar($curr->expr->key)) ) { $curr->expr->setAttribute('typephp_preceding_assign_expr', $prev->expr->expr); } } } + + /** + * Checks whether a yield key expression contains any assignment, increment/decrement, + * call, or other side-effecting node that could mutate local state before the yield value is evaluated. + */ + private static function exprMayMutateVar(Node\Expr $expr): bool + { + return (new \PhpParser\NodeFinder())->findFirst($expr, static function (Node $n): bool { + return $n instanceof Node\Expr\Assign + || $n instanceof Node\Expr\AssignOp + || $n instanceof Node\Expr\AssignRef + || $n instanceof Node\Expr\PreInc + || $n instanceof Node\Expr\PostInc + || $n instanceof Node\Expr\PreDec + || $n instanceof Node\Expr\PostDec + || $n instanceof Node\Expr\CallLike + || $n instanceof Node\Expr\Yield_ + || $n instanceof Node\Expr\YieldFrom + || $n instanceof Node\Expr\Eval_ + || $n instanceof Node\Expr\Include_; + }) !== null; + } } diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index d839eedc..5aa10566 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -3104,6 +3104,38 @@ public static function cloneWith( return $cloned; } + /** + * Evaluates PHP's native increment (++) semantics without mutating the caller's slot. + */ + public static function computeInc(mixed $value): mixed + { + if (\is_int($value) || \is_float($value)) { + return $value + 1; + } + + $copy = $value; + /** @phpstan-ignore preInc.type */ + ++$copy; + + return $copy; + } + + /** + * Evaluates PHP's native decrement (--) semantics without mutating the caller's slot. + */ + public static function computeDec(mixed $value): mixed + { + if (\is_int($value) || \is_float($value)) { + return $value - 1; + } + + $copy = $value; + /** @phpstan-ignore preDec.type */ + --$copy; + + return $copy; + } + /** * Infers a TypeNode AST representation from a raw PHP value. */ diff --git a/tests/Internal/Ast/ContractVisitorTest.php b/tests/Internal/Ast/ContractVisitorTest.php index d5a23edb..2fbc9e8d 100644 --- a/tests/Internal/Ast/ContractVisitorTest.php +++ b/tests/Internal/Ast/ContractVisitorTest.php @@ -93,8 +93,8 @@ class HookedClass { $transformed = $this->printer->prettyPrint($newStmts); - expect($transformed)->toContain('RuntimeTypeChecker::checkVariable($val + 1, \'positive-int\', \'val\'') - ->and($transformed)->toContain('RuntimeTypeChecker::checkVariable($val - 1, \'positive-int\', \'val\'') + expect($transformed)->toContain('RuntimeTypeChecker::checkVariable(\TypePHP\Internal\RuntimeTypeChecker::computeInc($val), \'positive-int\', \'val\'') + ->and($transformed)->toContain('RuntimeTypeChecker::checkVariable(\TypePHP\Internal\RuntimeTypeChecker::computeDec($val), \'positive-int\', \'val\'') ; }); @@ -398,8 +398,8 @@ public function enumMethod() { expect($transformed)->toContain("RuntimeTypeChecker::checkProperty(\$className::\$staticCount + 5, \$className, 'staticCount'") ->and($transformed)->toContain('$__typephpTgt0 = $getObj()') - ->and($transformed)->toContain("RuntimeTypeChecker::checkProperty(\$__typephpTgt0::\$staticCount + 1, \$__typephpTgt0, 'staticCount'") - ->and($transformed)->toContain("RuntimeTypeChecker::checkProperty(\$className::\$staticCount2 - 1, \$className, 'staticCount2'") + ->and($transformed)->toContain("RuntimeTypeChecker::checkProperty(\\TypePHP\\Internal\\RuntimeTypeChecker::computeInc(\$__typephpTgt0::\$staticCount), \$__typephpTgt0, 'staticCount'") + ->and($transformed)->toContain("RuntimeTypeChecker::checkProperty(\\TypePHP\\Internal\\RuntimeTypeChecker::computeDec(\$className::\$staticCount2), \$className, 'staticCount2'") ; }); diff --git a/tests/Internal/Ast/Elimination/FunctionContractEliminationEdgeCasesTest.php b/tests/Internal/Ast/Elimination/FunctionContractEliminationEdgeCasesTest.php new file mode 100644 index 00000000..b9d68712 --- /dev/null +++ b/tests/Internal/Ast/Elimination/FunctionContractEliminationEdgeCasesTest.php @@ -0,0 +1,174 @@ + + */ +function genYieldWithKeyPostDec(): Generator +{ + $val = 1; + yield ($val--) => $val; +} + +/** + * @return Generator + */ +function genYieldWithKeyAssignOp(): Generator +{ + $val = 1; + yield ($val -= 5) => $val; +} + +/** + * @return Generator + */ +function genYieldWithNestedKeyAssign(): Generator +{ + $val = 1; + yield ($tmp = ($val = -3)) => $val; +} + +/** + * @return Generator + */ +function genYieldWithKeyByRefCall(): Generator +{ + $val = 1; + yield mutateRefToNegative($val) => $val; +} + +/** + * @return Generator + */ +function genYieldWithPureKey(): Generator +{ + $key = 0; + $val = 42; + yield $key => $val; +} + +describe('FunctionContractInjector Static Elimination Edge Cases', function () { + afterEach(function () { + Config::reset(); + }); + + describe('Implicitly nullable native parameter (int $x = null) under strict nullability', function () { + test('does not eliminate setupScope for int $x = null when respect_native_nullability is false', function () { + $baseTmp = sys_get_temp_dir() . '/typephp_implicit_null_' . uniqid('', true); + mkdir($baseTmp, 0777, true); + $realBase = realpath($baseTmp); + $tmpDir = str_replace('\\', '/', $realBase !== false ? $realBase : $baseTmp); + $scriptPath = $tmpDir . '/implicit_nullable.php'; + + $source = <<<'PHP' + $includes, + 'respect_native_nullability' => false, + 'eliminate_statically_proven_checks' => true, + ]); + + set_error_handler(static fn (int $errno): bool => $errno === E_DEPRECATED, E_DEPRECATED); + + try { + $transformed = StreamWrapper::transformSource($source, $scriptPath); + + preg_match('/function strictImplicitNullReject\b.*?\{(.*?)\}/s', $transformed, $rejectMatch); + preg_match('/function strictImplicitNullExplicitDoc\b.*?\{(.*?)\}/s', $transformed, $allowMatch); + preg_match('/function strictImplicitNullReturnBypass\b.*?\{(.*?)\}/s', $transformed, $retMatch); + + expect($rejectMatch[1] ?? '')->toContain('setupScope'); + expect($allowMatch[1] ?? '')->not->toContain('setupScope'); + expect($retMatch[1] ?? '')->toContain('checkReturn'); + + require_once $scriptPath; + + expect(strictImplicitNullReject(5))->toBe(5); + expect(strictImplicitNullExplicitDoc(null))->toBeNull(); + expect(fn () => strictImplicitNullReject(null)) + ->toThrow(TypeError::class, 'Argument $x must be of type int') + ; + expect(strictImplicitNullReturnBypass(5))->toBe(5); + expect(fn () => strictImplicitNullReturnBypass(null)) + ->toThrow(TypeError::class, 'Return value must be of type int') + ; + } finally { + restore_error_handler(); + @unlink($scriptPath); + @rmdir($tmpDir); + } + }); + }); + + describe('Generator yield $key => $val preceding assignment tagging', function () { + test('does not eliminate checkYield when yield key mutates the yielded variable', function () { + expect(fn () => iterator_to_array(genYieldWithKeyPostDec())) + ->toThrow(TypeError::class, 'Return iterator value must be of type positive-int') + ; + + expect(fn () => iterator_to_array(genYieldWithKeyAssignOp())) + ->toThrow(TypeError::class, 'Return iterator value must be of type positive-int') + ; + + expect(fn () => iterator_to_array(genYieldWithNestedKeyAssign())) + ->toThrow(TypeError::class, 'Return iterator value must be of type positive-int') + ; + + expect(fn () => iterator_to_array(genYieldWithKeyByRefCall())) + ->toThrow(TypeError::class, 'Return iterator value must be of type positive-int') + ; + }); + + test('still eliminates checkYield when yield key is pure and preceding value is proven', function () { + expect(iterator_to_array(genYieldWithPureKey()))->toBe([0 => 42]); + + $transformed = StreamWrapper::transformSource((string) file_get_contents(__FILE__), __FILE__); + preg_match('/function genYieldWithPureKey\b.*?\{(.*?)\}/s', $transformed, $matches); + expect($matches[1] ?? '')->not->toContain('checkYield'); + }); + }); +}); diff --git a/tests/TypeChecking/Boundaries/AssignOpPrecedenceTest.php b/tests/TypeChecking/Boundaries/AssignOpPrecedenceTest.php index fe0d18d1..18a9ab3e 100644 --- a/tests/TypeChecking/Boundaries/AssignOpPrecedenceTest.php +++ b/tests/TypeChecking/Boundaries/AssignOpPrecedenceTest.php @@ -177,6 +177,8 @@ public function init(): void $transformed = StreamWrapper::transformSource($source, 'precedence_button_test.php'); - expect($transformed)->toContain("\$this->tooltip ?? (\$this->direction === 'up' ? 'VALIDATE' : 'CANCEL')"); + expect($transformed)->toContain('$this->tooltip ?? ($this->tooltip =') + ->and($transformed)->toContain("checkProperty(\$this->direction === 'up' ? 'VALIDATE' : 'CANCEL'") + ; }); }); diff --git a/tests/TypeChecking/Boundaries/IncDecAndCoalesceAssignSoundnessTest.php b/tests/TypeChecking/Boundaries/IncDecAndCoalesceAssignSoundnessTest.php new file mode 100644 index 00000000..c8df5ec4 --- /dev/null +++ b/tests/TypeChecking/Boundaries/IncDecAndCoalesceAssignSoundnessTest.php @@ -0,0 +1,328 @@ + $old, 'new' => $local]; +} + +/** + * @param ?positive-int $val + */ +function decNullablePositiveInt(?int $val): ?int +{ + /** @var ?positive-int $local */ + $local = $val; + $local--; + + return $local; +} + +/** + * @param ?positive-int $val + */ +function incNullablePositiveInt(?int $val): int +{ + /** @var ?positive-int $local */ + $local = $val; + $local++; + + return $local; +} + +function incBoolVar(bool $flag): bool +{ + /** @var bool $local */ + $local = $flag; + $local++; + + return $local; +} + +/** + * @param positive-int $n + */ +function decPositiveIntToZero(int $n): int +{ + /** @var positive-int $local */ + $local = $n; + $local--; + + return $local; +} + +final class CoalesceReadonlyPropertyFixture +{ + /** + * @var positive-int + */ + public readonly ?int $id; + + /** + * @var ?positive-int + */ + public ?int $count = null; + + public int $setCount = 0; + + public function __construct(?int $initialId = null, ?int $initialCount = null) + { + if ($initialId !== null) { + $this->id = $initialId; + } + $this->count = $initialCount; + } + + public function coalesceReadonlyId(int $fallback): int + { + return $this->id ??= $fallback; + } + + public function coalesceCount(callable $factory): ?int + { + return $this->count ??= $factory(); + } + + public function coalesceWithSideEffectTarget(callable $getSelf, int $fallback): ?int + { + return ($getSelf())->count ??= $fallback; + } +} + +describe('Increment/Decrement and Coalesce-Assign (??=) Semantic Preservation', function () { + describe('++ / -- preserves native PHP semantics for strings, null, and bools', function () { + test('increments alphanumeric strings instead of crashing with string + int TypeError', function () { + $a = null; + $z = null; + $item = null; + $post = null; + + set_error_handler(static fn (int $errno): bool => $errno === E_DEPRECATED, E_DEPRECATED); + + try { + $a = incNonEmptyString('a'); + $z = incNonEmptyString('z'); + $item = incNonEmptyString('item09'); + $post = postIncStringWithReturn('a'); + } finally { + restore_error_handler(); + } + + expect($a)->toBe('b'); + expect($z)->toBe('aa'); + expect($item)->toBe('item10'); + expect($post)->toBe(['old' => 'a', 'new' => 'b']); + }); + + test('preserves null on decrement instead of converting null into -1', function () { + $result = null; + set_error_handler(static fn (int $errno): bool => $errno === E_DEPRECATED, E_DEPRECATED); + + try { + $result = decNullablePositiveInt(null); + } finally { + restore_error_handler(); + } + + expect($result)->toBeNull(); + expect(incNullablePositiveInt(null))->toBe(1); + }); + + test('preserves bool on increment instead of coercing bool + 1 to int(2)', function () { + $result = null; + set_error_handler(static fn (int $errno): bool => $errno === E_DEPRECATED, E_DEPRECATED); + + try { + $result = incBoolVar(true); + } finally { + restore_error_handler(); + } + + expect($result)->toBeTrue(); + }); + + test('still catches genuine contract violations on decremented integers', function () { + expect(fn () => decPositiveIntToZero(1)) + ->toThrow(TypeError::class, 'must be of type positive-int') + ; + }); + }); + + describe('??= (Coalesce-Assign) preserves short-circuiting and non-reassignment semantics', function () { + test('does not rewrite already-initialized readonly property on ??=', function () { + $obj = new CoalesceReadonlyPropertyFixture(initialId: 10); + + expect($obj->coalesceReadonlyId(20))->toBe(10); + expect($obj->id)->toBe(10); + }); + + test('initializes uninitialized readonly property on ??= and validates contract', function () { + $obj = new CoalesceReadonlyPropertyFixture(); + expect($obj->coalesceReadonlyId(25))->toBe(25); + expect($obj->id)->toBe(25); + + $obj2 = new CoalesceReadonlyPropertyFixture(); + expect(fn () => $obj2->coalesceReadonlyId(-5)) + ->toThrow(TypeError::class, 'must be of type positive-int') + ; + }); + + test('does not evaluate RHS factory when target is already non-null, and enforces contract when null', function () { + $obj = new CoalesceReadonlyPropertyFixture(initialCount: 7); + $calls = 0; + + $res = $obj->coalesceCount(function () use (&$calls): int { + $calls++; + + return 99; + }); + + expect($res)->toBe(7); + expect($calls)->toBe(0); + + $nullObj = new CoalesceReadonlyPropertyFixture(initialCount: null); + expect(function () use ($nullObj, &$calls): void { + $nullObj->coalesceCount(function () use (&$calls): int { + $calls++; + + return -3; + }); + })->toThrow(TypeError::class, 'must be of type positive-int'); + + expect($calls)->toBe(1); + }); + + test('does not trigger PHP 8.4 property set hook when hooked property is already non-null on ??=', function () { + if (\PHP_VERSION_ID < 80400) { + expect(true)->toBeTrue(); + + return; + } + + $baseTmp = sys_get_temp_dir() . '/typephp_coalesce_hook_' . uniqid('', true); + mkdir($baseTmp, 0777, true); + $realBase = realpath($baseTmp); + $tmpDir = str_replace('\\', '/', $realBase !== false ? $realBase : $baseTmp); + $scriptPath = $tmpDir . '/hook_coalesce.php'; + + file_put_contents($scriptPath, <<<'PHP' +setCalls++; + $this->score = $val; + } + } + + public function coalesceScore(int $fallback): ?int + { + return $this->score ??= $fallback; + } +} + +$obj = new HookedCoalesceFixture(); +$afterNonNull = $obj->coalesceScore(20); +$setsAfterNonNull = $obj->setCalls; + +$obj->score = null; +$setsAfterReset = $obj->setCalls; +$afterNull = $obj->coalesceScore(30); +$setsAfterAssign = $obj->setCalls; + +return [ + 'afterNonNull' => $afterNonNull, + 'setsAfterNonNull' => $setsAfterNonNull, + 'setsAfterReset' => $setsAfterReset, + 'afterNull' => $afterNull, + 'setsAfterAssign' => $setsAfterAssign, +]; +PHP); + + $currentIncludes = TypePHP\Internal\Util\Config::get()['include'] ?? []; + $includes = \is_array($currentIncludes) ? $currentIncludes : []; + $includes[] = $tmpDir . '/**'; + TypePHP\Internal\Util\Config::set(['include' => $includes]); + + try { + /** @var array{afterNonNull: ?int, setsAfterNonNull: int, setsAfterReset: int, afterNull: ?int, setsAfterAssign: int} $res */ + $res = require $scriptPath; + + expect($res['afterNonNull'])->toBe(10); + expect($res['setsAfterNonNull'])->toBe(0); + expect($res['setsAfterReset'])->toBe(1); + expect($res['afterNull'])->toBe(30); + expect($res['setsAfterAssign'])->toBe(2); + } finally { + TypePHP\Internal\Util\Config::reset(); + @unlink($scriptPath); + @rmdir($tmpDir); + } + }); + + test('evaluates impure target base once on ??= and preserves valid operator precedence in compound expressions', function () { + $obj = new CoalesceReadonlyPropertyFixture(initialCount: null); + $targetCalls = 0; + + $res = $obj->coalesceWithSideEffectTarget(function () use ($obj, &$targetCalls): CoalesceReadonlyPropertyFixture { + $targetCalls++; + + return $obj; + }, 15); + + expect($targetCalls)->toBe(1); + expect($res)->toBe(15); + expect($obj->count)->toBe(15); + + $source = <<<'PHP' +parse($transformed); + expect($tokens)->not->toBeNull(); + expect($transformed)->toContain('?? ($x ='); + }); + }); +}); From 38adb7b588cc5bfd57c51ba57743978d58e5a7ac Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sat, 5 Dec 2026 01:19:22 +0800 Subject: [PATCH 11/24] Add PropertyOpcodeParityTest to validate opcode and bitmask parity between MemberAssignChecker and RuntimeTypeChecker --- .../Checker/PropertyOpcodeParityTest.php | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 tests/Internal/Checker/PropertyOpcodeParityTest.php diff --git a/tests/Internal/Checker/PropertyOpcodeParityTest.php b/tests/Internal/Checker/PropertyOpcodeParityTest.php new file mode 100644 index 00000000..dbcf8efd --- /dev/null +++ b/tests/Internal/Checker/PropertyOpcodeParityTest.php @@ -0,0 +1,63 @@ +getConstants() as $name => $value) { + if (str_starts_with($name, 'OP_') && $name !== 'OP_FALLBACK') { + $memberOps[$name] = $value; + } + } + + $runtimeOps = []; + foreach ($runtimeRef->getConstants() as $name => $value) { + if (str_starts_with($name, 'PROP_OP_')) { + $runtimeOps[substr($name, 5)] = $value; + } + } + + expect($memberOps)->not->toBeEmpty(); + expect($runtimeOps)->toBe($memberOps); + }); + + test('all RuntimeTypeChecker PROP_BIT_* constants match MemberAssignChecker BIT_* constants and are distinct powers of two', function () { + $memberRef = new ReflectionClass(MemberAssignChecker::class); + $runtimeRef = new ReflectionClass(RuntimeTypeChecker::class); + + $memberBits = []; + foreach ($memberRef->getConstants() as $name => $value) { + if (str_starts_with($name, 'BIT_')) { + $memberBits[$name] = $value; + } + } + + $runtimeBits = []; + foreach ($runtimeRef->getConstants() as $name => $value) { + if (str_starts_with($name, 'PROP_BIT_')) { + $runtimeBits[substr($name, 5)] = $value; + } + } + + expect($memberBits)->not->toBeEmpty(); + expect($runtimeBits)->toBe($memberBits); + + $combinedMask = 0; + foreach ($memberBits as $name => $bit) { + expect($bit)->toBeInt() + ->and($bit)->toBeGreaterThan(0) + ->and(($bit & ($bit - 1)))->toBe(0, "{$name} must be a power of two") + ->and(($combinedMask & $bit))->toBe(0, "{$name} collides with another bitmask") + ; + + $combinedMask |= $bit; + } + }); +}); \ No newline at end of file From 449f9a8c5ee8a32f559dffece9d86a94c8dcaaf3 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sat, 5 Dec 2026 01:19:57 +0800 Subject: [PATCH 12/24] Update cache version prefix to v0.15.0 --- src/Internal/Io/CacheManager.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Internal/Io/CacheManager.php b/src/Internal/Io/CacheManager.php index e86556d5..7debc68f 100644 --- a/src/Internal/Io/CacheManager.php +++ b/src/Internal/Io/CacheManager.php @@ -17,7 +17,7 @@ final class CacheManager /** * Cache version prefix string. Bump this whenever AST printer/transformation rules change. */ - public const VERSION_PREFIX = 'v0.14.4_'; + public const VERSION_PREFIX = 'v0.15.0_'; /** * Config keys that only steer runtime behaviour and never change the transformed source. From 7298f6e093a4088ad91f8a0f0d12accf4fca7279 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sat, 5 Dec 2026 01:34:42 +0800 Subject: [PATCH 13/24] Enhance multiline handling in ContractVisitor and TypePHPPrinter; add tests for line number preservation in generic constructor calls --- src/Internal/Ast/ContractVisitor.php | 8 ++ src/Internal/Ast/TypePHPPrinter.php | 44 +++++++++++ src/Internal/Io/StreamWrapper.php | 12 ++- .../Checker/PropertyOpcodeParityTest.php | 2 +- tests/Unit/LineNumberPreservationTest.php | 73 +++++++++++++++++++ 5 files changed, 131 insertions(+), 8 deletions(-) diff --git a/src/Internal/Ast/ContractVisitor.php b/src/Internal/Ast/ContractVisitor.php index d869aff5..474fea39 100644 --- a/src/Internal/Ast/ContractVisitor.php +++ b/src/Internal/Ast/ContractVisitor.php @@ -2035,6 +2035,14 @@ private function handleAssign(Node\Expr\Assign $node): ?Node ] ); + if ($expr->getEndLine() > $expr->getStartLine() && $expr->getStartLine() > 0) { + $wrappedNew->setAttribute('typephp_multiline_call', [ + 'startLine' => $expr->getStartLine(), + 'endLine' => $expr->getEndLine(), + 'forwardedStartIndex' => 3, + ]); + } + $node->expr = $this->wrapVariableCheck($wrappedNew, $typeString, $varName, $node->var->getStartLine()); return null; diff --git a/src/Internal/Ast/TypePHPPrinter.php b/src/Internal/Ast/TypePHPPrinter.php index f867ab38..0db755a7 100644 --- a/src/Internal/Ast/TypePHPPrinter.php +++ b/src/Internal/Ast/TypePHPPrinter.php @@ -40,6 +40,10 @@ protected function p( return '(' . parent::p($node, PrettyPrinterAbstract::MAX_PRECEDENCE, PrettyPrinterAbstract::MAX_PRECEDENCE, $parentFormatPreserved) . ')'; } + if ($node instanceof Node\Expr\StaticCall && $node->getAttribute('typephp_multiline_call') !== null) { + return $this->printMultilineStaticCall($node); + } + $output = parent::p($node, $precedence, $lhsPrecedence, $parentFormatPreserved); if ($node instanceof Node\Stmt && $node->getAttribute('typephp_injected') === true) { @@ -49,6 +53,46 @@ protected function p( return $output; } + /** + * Prints a wrapped constructor StaticCall while preserving the exact start/end lines + * of its forwarded multi-line constructor arguments. + */ + private function printMultilineStaticCall(Node\Expr\StaticCall $node): string + { + /** @var array{startLine: int, endLine: int, forwardedStartIndex: int} $info */ + $info = $node->getAttribute('typephp_multiline_call'); + $startLine = $info['startLine']; + $endLine = $info['endLine']; + $fwdStart = $info['forwardedStartIndex']; + + $prefixArgs = []; + for ($i = 0; $i < $fwdStart && isset($node->args[$i]); $i++) { + $prefixArgs[] = $this->p($node->args[$i]); + } + + $output = $this->p($node->class) . '::' . $this->p($node->name) . '(' . implode(', ', $prefixArgs); + $cursorLine = $startLine + substr_count($output, "\n"); + + $totalArgs = \count($node->args); + for ($i = $fwdStart; $i < $totalArgs; $i++) { + $arg = $node->args[$i]; + $comments = $arg->getComments(); + $argStartLine = $comments !== [] ? $comments[0]->getStartLine() : $arg->getStartLine(); + $leadingNewlines = ($argStartLine > $cursorLine) ? ($argStartLine - $cursorLine) : 0; + + $printedArg = $this->p($arg); + $argNewlines = substr_count($printedArg, "\n"); + + $output .= ($leadingNewlines > 0 ? ',' . str_repeat("\n", $leadingNewlines) : ', ') . $printedArg; + $cursorLine += $leadingNewlines + $argNewlines; + } + + $trailingNewlines = ($endLine > $cursorLine) ? ($endLine - $cursorLine) : 0; + $output .= str_repeat("\n", $trailingNewlines) . ')'; + + return $output; + } + /** * Converts single-line comments and squashes whitespace on injected statements * without altering string literals or attribute tokens. diff --git a/src/Internal/Io/StreamWrapper.php b/src/Internal/Io/StreamWrapper.php index 48442a9b..9483e4d9 100644 --- a/src/Internal/Io/StreamWrapper.php +++ b/src/Internal/Io/StreamWrapper.php @@ -307,19 +307,17 @@ public static function transformSource(string $source, string $filePath = ''): s $transformed = self::neutralizeTrailingLineComments($transformed); - $transformedLineCount = substr_count($transformed, "\n"); - $drift = $transformedLineCount - $originalLineCount; - - if ($drift > 0) { + if (str_contains($transformed, '/*__TYPEPHP_INJECTED_START__*/')) { $transformed = preg_replace( '/[ \t]*\r?\n[ \t]*\/\*__TYPEPHP_INJECTED_START__\*\//', ' /*__TYPEPHP_INJECTED_START__*/', - $transformed, - $drift + $transformed ) ?? $transformed; - $drift = substr_count($transformed, "\n") - $originalLineCount; } + $transformedLineCount = substr_count($transformed, "\n"); + $drift = $transformedLineCount - $originalLineCount; + if ($drift < 0) { $nl = str_contains($transformed, "\r\n") ? "\r\n" : "\n"; $transformed .= str_repeat($nl, abs($drift)); diff --git a/tests/Internal/Checker/PropertyOpcodeParityTest.php b/tests/Internal/Checker/PropertyOpcodeParityTest.php index dbcf8efd..9f252daa 100644 --- a/tests/Internal/Checker/PropertyOpcodeParityTest.php +++ b/tests/Internal/Checker/PropertyOpcodeParityTest.php @@ -60,4 +60,4 @@ $combinedMask |= $bit; } }); -}); \ No newline at end of file +}); diff --git a/tests/Unit/LineNumberPreservationTest.php b/tests/Unit/LineNumberPreservationTest.php index 6f726dd3..1dde1ca3 100644 --- a/tests/Unit/LineNumberPreservationTest.php +++ b/tests/Unit/LineNumberPreservationTest.php @@ -1204,5 +1204,78 @@ function inlineCommentBeforeUnset(): void ->and($transAfterIdx)->toBe($origAfterIdx) ; }); + + test('preserves exact internal line numbers for multi-line generic constructor calls with multiple arguments', function () { + $source = <<<'PHP' + + */ +$pair = new Pair(1, 1); + +/** + * @var Pair + */ +$pair = new Pair( + 1, + 2, +); + +$afterMultiLinePair = true; +PHP; + + $transformed = StreamWrapper::transformSource($source, 'test_multiline_generic_pair.php'); + + $origLines = explode("\n", str_replace("\r\n", "\n", $source)); + $transLines = explode("\n", str_replace("\r\n", "\n", $transformed)); + + expect(\count($transLines))->toBe(\count($origLines)); + + $findLineIndex = static function (string $needle, array $lines): int { + foreach ($lines as $idx => $line) { + if (str_contains($line, $needle)) { + return $idx; + } + } + + return -1; + }; + + expect($findLineIndex('public function __construct(', $transLines)) + ->toBe($findLineIndex('public function __construct(', $origLines)) + ; + expect($findLineIndex('@var Pair', $transLines)) + ->toBe($findLineIndex('@var Pair', $origLines)) + ; + expect($findLineIndex('$pair = new Pair(1, 1);', $origLines))->toBe(21); + expect($transLines[21])->toContain("withPendingGeneric('Pair'"); + expect($findLineIndex('@var Pair', $transLines)) + ->toBe($findLineIndex('@var Pair', $origLines)) + ; + expect($transLines[26])->toContain("withPendingGeneric('Pair'"); + expect(trim($transLines[27]))->toBe('1,'); + expect(trim($transLines[28]))->toBe('2'); + expect($transLines[29])->toStartWith('),'); + expect($findLineIndex('$afterMultiLinePair = true;', $transLines)) + ->toBe($findLineIndex('$afterMultiLinePair = true;', $origLines)) + ; + }); }); }); From a80592813df214182622839029ed710d07b507c0 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sat, 5 Dec 2026 02:15:07 +0800 Subject: [PATCH 14/24] Add support for additional scalar types and refine type resolution in InlineChecker and SpecialTypeResolver; introduce tests for inline routing and scalar refinements --- src/Internal/Checker/InlineChecker.php | 68 ++- src/Internal/Resolver/SpecialTypeResolver.php | 7 + .../InlineVarConfigRoutingTest.php | 512 ++++++++++++++++++ 3 files changed, 572 insertions(+), 15 deletions(-) create mode 100644 tests/TypeChecking/Configuration/InlineVarConfigRoutingTest.php diff --git a/src/Internal/Checker/InlineChecker.php b/src/Internal/Checker/InlineChecker.php index fe234a7a..f0b159f6 100644 --- a/src/Internal/Checker/InlineChecker.php +++ b/src/Internal/Checker/InlineChecker.php @@ -147,6 +147,7 @@ public static function reset(): void 'false' => true, 'scalar' => true, 'numeric' => true, + 'number' => true, 'positive-int' => true, 'negative-int' => true, 'non-positive-int' => true, @@ -164,18 +165,43 @@ public static function reset(): void 'non-empty-lowercase-string' => true, 'uppercase-string' => true, 'non-empty-uppercase-string' => true, + 'literal-string' => true, + 'truthy-string' => true, + 'non-falsy-string' => true, + 'class-string' => true, + 'interface-string' => true, + 'trait-string' => true, + 'enum-string' => true, + 'callable-string' => true, 'truthy' => true, 'falsy' => true, + 'falsey' => true, 'array-key' => true, ]; /** - * Fast lookup set for iterable types. + * Fast lookup set for built-in generic types representing scalar refinements rather than generic objects. + */ + private const SCALAR_GENERIC_TYPES = [ + 'int' => true, + 'integer' => true, + 'int-mask' => true, + 'int-mask-of' => true, + 'class-string' => true, + 'key-of' => true, + 'value-of' => true, + ]; + + /** + * Fast lookup set for iterable and collection array types. */ private const ARRAY_TYPES = [ 'array' => true, 'list' => true, 'iterable' => true, + 'non-empty-array' => true, + 'non-empty-list' => true, + 'non-empty-array-list' => true, ]; /** @@ -221,13 +247,15 @@ public static function checkVariable( $context = ($varName === 'return') ? 'Return value' : "Variable \$$varName"; + $isObjectGeneric = false; if ($typeNode instanceof GenericTypeNode) { $baseName = strtolower((string) $typeNode->type); - $isCollection = isset(self::ARRAY_TYPES[$baseName]); + $isObjectGeneric = ! isset(self::ARRAY_TYPES[$baseName]) && ! isset(self::SCALAR_GENERIC_TYPES[$baseName]); - if (! $isCollection) { + if ($isObjectGeneric) { if (! Config::isInlineGenericsEnabled() && Config::isInlineObjectsEnabled()) { $typeNode = $typeNode->type; + $isObjectGeneric = false; } elseif (! Config::isInlineGenericsEnabled() && ! Config::isInlineObjectsEnabled()) { return $value; } @@ -235,11 +263,11 @@ public static function checkVariable( } $preExistingBindings = null; - if (($fallbackMeta[0] === -1 || $fallbackMeta[1] !== []) && \is_object($value) && $typeNode instanceof GenericTypeNode) { + if ($isObjectGeneric && ($fallbackMeta[0] === -1 || $fallbackMeta[1] !== []) && \is_object($value) && $typeNode instanceof GenericTypeNode) { $preExistingBindings = TemplateManager::getConcreteInstanceBindings($value); } - if ($typeNode instanceof GenericTypeNode && Config::isInlineGenericsEnabled() && \is_object($value)) { + if ($isObjectGeneric && Config::isInlineGenericsEnabled() && \is_object($value) && $typeNode instanceof GenericTypeNode) { $err = TemplateManager::bindInstanceFromNode($value, $typeNode, $context); if ($err !== null) { return $err; @@ -255,16 +283,18 @@ public static function checkVariable( TemplateManager::markFallbackReturnBindings($value, $typeNode, $fallbackMeta[1], $fallbackMeta[0], $preExistingBindings); } - if ($typeNode instanceof CallableTypeNode || ($typeNode instanceof IdentifierTypeNode && strtolower($typeNode->name) === 'callable')) { - $cbPrefix = ($varName === 'return') ? 'Return value: Callback' : "Variable \$$varName: Callback"; + if (Config::isInlineCallablesEnabled()) { + if ($typeNode instanceof CallableTypeNode || ($typeNode instanceof IdentifierTypeNode && strtolower($typeNode->name) === 'callable')) { + $cbPrefix = ($varName === 'return') ? 'Return value: Callback' : "Variable \$$varName: Callback"; - return CallableWrapper::wrapTypeNode($typeNode, $value, $cbPrefix, $registry); - } + return CallableWrapper::wrapTypeNode($typeNode, $value, $cbPrefix, $registry); + } - if ($typeNode instanceof ArrayShapeNode && \is_array($value)) { - $value = self::wrapShapeCallables($typeNode, $value, $context, $registry); - } elseif (\is_array($value)) { - $value = self::wrapCollectionCallables($typeNode, $value, $context, $registry); + if ($typeNode instanceof ArrayShapeNode && \is_array($value)) { + $value = self::wrapShapeCallables($typeNode, $value, $context, $registry); + } elseif (\is_array($value)) { + $value = self::wrapCollectionCallables($typeNode, $value, $context, $registry); + } } } catch (\Throwable $e) { DebugLog::swallowed($e); // @codeCoverageIgnore @@ -441,8 +471,12 @@ private static function wrapShapeCallables(ArrayShapeNode $shapeNode, array $val */ private static function wrapCollectionCallables(TypeNode $typeNode, array $value, string $context, TypeValidatorRegistry $registry): array { + while ($typeNode instanceof NullableTypeNode) { + $typeNode = $typeNode->type; + } + $innerCallable = null; - if ($typeNode instanceof GenericTypeNode && \in_array(strtolower((string) $typeNode->type), ['list', 'array', 'iterable'], true)) { + if ($typeNode instanceof GenericTypeNode && isset(self::ARRAY_TYPES[strtolower((string) $typeNode->type)])) { $innerCallable = $typeNode->genericTypes[1] ?? $typeNode->genericTypes[0] ?? null; } elseif ($typeNode instanceof ArrayTypeNode) { $innerCallable = $typeNode->type; @@ -1138,7 +1172,7 @@ private static function shouldValidateType(TypeNode $node): bool return false; } - if ($lower === 'callable') { + if ($lower === 'callable' || $lower === 'pure-callable' || $lower === 'static-closure' || $lower === 'static-pure-closure') { return Config::isInlineCallablesEnabled(); } @@ -1159,6 +1193,10 @@ private static function shouldValidateType(TypeNode $node): bool return $checkArrays; } + if (isset(self::SCALAR_GENERIC_TYPES[$lower])) { + return Config::isInlineScalarsEnabled(); + } + if (Config::isInlineGenericsEnabled()) { return true; } diff --git a/src/Internal/Resolver/SpecialTypeResolver.php b/src/Internal/Resolver/SpecialTypeResolver.php index 7f0f0941..5ab905d8 100644 --- a/src/Internal/Resolver/SpecialTypeResolver.php +++ b/src/Internal/Resolver/SpecialTypeResolver.php @@ -54,6 +54,7 @@ final class SpecialTypeResolver 'list' => true, 'object' => true, 'callable' => true, + 'pure-callable' => true, 'iterable' => true, 'resource' => true, 'null' => true, @@ -93,8 +94,14 @@ final class SpecialTypeResolver 'array-key' => true, 'literal-string' => true, 'truthy-string' => true, + 'non-falsy-string' => true, 'non-empty-array' => true, 'non-empty-list' => true, + 'non-empty-array-list' => true, + 'key-of' => true, + 'value-of' => true, + 'int-mask' => true, + 'int-mask-of' => true, 'number' => true, 'numeric' => true, 'truthy' => true, diff --git a/tests/TypeChecking/Configuration/InlineVarConfigRoutingTest.php b/tests/TypeChecking/Configuration/InlineVarConfigRoutingTest.php new file mode 100644 index 00000000..065d9b81 --- /dev/null +++ b/tests/TypeChecking/Configuration/InlineVarConfigRoutingTest.php @@ -0,0 +1,512 @@ + + */ + public mixed $nonEmptyIntList = null; + + /** + * @var class-string + */ + public mixed $classString = null; +} + +/** + * @template T + */ +final class InlineConfigRoutingGenericBox +{ + /** + * @var T + */ + public mixed $value = null; + + /** + * @param T $value + */ + public function set(mixed $value): void + { + $this->value = $value; + } +} + +function testInlineRoutingNonEmptyArray(mixed $val): mixed +{ + /** @var non-empty-array $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingNonEmptyList(mixed $val): mixed +{ + /** @var non-empty-list $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingGenericNonEmptyList(mixed $val): mixed +{ + /** @var non-empty-list $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingGenericNonEmptyArray(mixed $val): mixed +{ + /** @var non-empty-array $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingNonEmptyCallableList(mixed $val): mixed +{ + /** @var non-empty-list $callbacks */ + $callbacks = $val; + + return $callbacks; +} + +function testInlineRoutingNumber(mixed $val): mixed +{ + /** @var number $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingLiteralString(mixed $val): mixed +{ + /** @var literal-string $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingTruthyString(mixed $val): mixed +{ + /** @var truthy-string $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingNonFalsyString(mixed $val): mixed +{ + /** @var non-falsy-string $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingFalsey(mixed $val): mixed +{ + /** @var falsey $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingClassString(mixed $val): mixed +{ + /** @var class-string $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingInterfaceString(mixed $val): mixed +{ + /** @var interface-string $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingTraitString(mixed $val): mixed +{ + /** @var trait-string $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingEnumString(mixed $val): mixed +{ + /** @var enum-string $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingCallableString(mixed $val): mixed +{ + /** @var callable-string $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingIntRange(mixed $val): mixed +{ + /** @var int<1, 10> $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingIntMask(mixed $val): mixed +{ + /** @var int-mask<1, 2, 4> $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingGenericClassString(mixed $val): mixed +{ + /** @var class-string $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingKeyOf(mixed $val): mixed +{ + /** @var key-of $x */ + $x = $val; + + return $x; +} + +function testInlineRoutingStdClass(mixed $val): mixed +{ + /** @var stdClass $x */ + $x = $val; + + return $x; +} + +describe('InlineChecker Config Routing (inline_vars)', function () { + $originalInlineVars = null; + + beforeEach(function () use (&$originalInlineVars) { + $originalInlineVars = TypePHP::getConfig()['inline_vars']; + }); + + afterEach(function () use (&$originalInlineVars) { + TypePHP::setConfig(['inline_vars' => $originalInlineVars]); + }); + + describe('Array Refinements (non-empty-array, non-empty-list)', function () { + test('enforces non-empty-array and non-empty-list when only arrays (+ properties) are enabled', function () { + TypePHP::setConfig([ + 'inline_vars' => [ + 'properties' => true, + 'arrays' => true, + 'scalars' => false, + 'objects' => false, + 'generics' => false, + 'callables' => false, + ], + ]); + + expect(testInlineRoutingNonEmptyArray(['a' => 1]))->toBe(['a' => 1]); + expect(testInlineRoutingNonEmptyList([1, 2]))->toBe([1, 2]); + expect(testInlineRoutingGenericNonEmptyList([1, 2]))->toBe([1, 2]); + expect(testInlineRoutingGenericNonEmptyArray(['a' => 1]))->toBe(['a' => 1]); + + expect(fn () => testInlineRoutingNonEmptyArray([])) + ->toThrow(TypeError::class, 'Variable $x must be of type non-empty-array') + ; + + expect(fn () => testInlineRoutingNonEmptyList([])) + ->toThrow(TypeError::class, 'Variable $x must be of type non-empty-list') + ; + + expect(fn () => testInlineRoutingGenericNonEmptyList([])) + ->toThrow(TypeError::class, 'Variable $x must be a non-empty list') + ; + + expect(fn () => testInlineRoutingGenericNonEmptyList(['bad'])) + ->toThrow(TypeError::class, 'Variable $x[0] must be of type int') + ; + + expect(fn () => testInlineRoutingGenericNonEmptyArray(['a' => 'bad'])) + ->toThrow(TypeError::class, "Variable \$x['a'] must be of type int") + ; + + $holder = new InlineConfigRoutingHolder(); + expect(fn () => $holder->nonEmptyIntList = ['bad']) + ->toThrow(TypeError::class, 'Property InlineConfigRoutingHolder::$nonEmptyIntList[0] must be of type int') + ; + }); + + test('does not downgrade generic non-empty-list/non-empty-array element types when generics is disabled and objects is enabled', function () { + TypePHP::setConfig([ + 'inline_vars' => [ + 'properties' => true, + 'arrays' => true, + 'objects' => true, + 'generics' => false, + 'scalars' => false, + 'callables' => false, + ], + ]); + + expect(fn () => testInlineRoutingGenericNonEmptyList(['not-an-int'])) + ->toThrow(TypeError::class, 'Variable $x[0] must be of type int') + ; + + expect(fn () => testInlineRoutingGenericNonEmptyArray(['a' => 'not-an-int'])) + ->toThrow(TypeError::class, "Variable \$x['a'] must be of type int") + ; + }); + + test('skips non-empty-array and non-empty-list when arrays is disabled even if objects and generics are enabled', function () { + TypePHP::setConfig([ + 'inline_vars' => [ + 'properties' => true, + 'arrays' => false, + 'objects' => true, + 'generics' => true, + 'scalars' => false, + 'callables' => false, + ], + ]); + + expect(testInlineRoutingNonEmptyArray([]))->toBe([]); + expect(testInlineRoutingNonEmptyList([]))->toBe([]); + expect(testInlineRoutingGenericNonEmptyList(['bad']))->toBe(['bad']); + expect(testInlineRoutingGenericNonEmptyArray(['a' => 'bad']))->toBe(['a' => 'bad']); + + // Sanity check: actual object types are still enforced + expect(fn () => testInlineRoutingStdClass('not-an-object')) + ->toThrow(TypeError::class, 'Variable $x must be of type stdClass') + ; + }); + + test('wraps callables inside non-empty-list', function () { + TypePHP::setConfig([ + 'inline_vars' => [ + 'properties' => true, + 'arrays' => true, + 'callables' => true, + 'objects' => false, + 'generics' => false, + 'scalars' => false, + ], + ]); + + $callbacks = testInlineRoutingNonEmptyCallableList([ + static fn ($n) => (string) $n, + ]); + + expect($callbacks[0](42))->toBe('42'); + expect(fn () => $callbacks[0]('not-an-int')) + ->toThrow(TypeError::class, 'must be of type int') + ; + }); + }); + + describe('Scalar Refinement Identifiers', function () { + test('enforces all scalar refinement identifiers when only scalars (+ properties) are enabled', function () { + TypePHP::setConfig([ + 'inline_vars' => [ + 'properties' => true, + 'scalars' => true, + 'arrays' => false, + 'objects' => false, + 'generics' => false, + 'callables' => false, + ], + ]); + + // Valid values pass + expect(testInlineRoutingNumber(3.14))->toBe(3.14); + expect(testInlineRoutingLiteralString('abc'))->toBe('abc'); + expect(testInlineRoutingTruthyString('yes'))->toBe('yes'); + expect(testInlineRoutingNonFalsyString('yes'))->toBe('yes'); + expect(testInlineRoutingFalsey(''))->toBe(''); + expect(testInlineRoutingClassString(stdClass::class))->toBe(stdClass::class); + expect(testInlineRoutingInterfaceString(Throwable::class))->toBe(Throwable::class); + expect(testInlineRoutingTraitString(InlineConfigRoutingTestTrait::class))->toBe(InlineConfigRoutingTestTrait::class); + expect(testInlineRoutingEnumString(InlineConfigRoutingTestEnum::class))->toBe(InlineConfigRoutingTestEnum::class); + expect(testInlineRoutingCallableString('strlen'))->toBe('strlen'); + + // Invalid values throw + expect(fn () => testInlineRoutingNumber('not-a-number')) + ->toThrow(TypeError::class, 'Variable $x must be of type number') + ; + expect(fn () => testInlineRoutingLiteralString(123)) + ->toThrow(TypeError::class, 'Variable $x must be of type literal-string') + ; + expect(fn () => testInlineRoutingTruthyString('0')) + ->toThrow(TypeError::class, 'Variable $x must be of type truthy-string') + ; + expect(fn () => testInlineRoutingNonFalsyString('0')) + ->toThrow(TypeError::class, 'Variable $x must be of type non-falsy-string') + ; + expect(fn () => testInlineRoutingFalsey('truthy')) + ->toThrow(TypeError::class, 'Variable $x must be of type falsey') + ; + expect(fn () => testInlineRoutingClassString('NotARealClass')) + ->toThrow(TypeError::class, 'Variable $x must be of type class-string') + ; + expect(fn () => testInlineRoutingInterfaceString(stdClass::class)) + ->toThrow(TypeError::class, 'Variable $x must be of type interface-string') + ; + expect(fn () => testInlineRoutingTraitString(stdClass::class)) + ->toThrow(TypeError::class, 'Variable $x must be of type trait-string') + ; + expect(fn () => testInlineRoutingEnumString(stdClass::class)) + ->toThrow(TypeError::class, 'Variable $x must be of type enum-string') + ; + expect(fn () => testInlineRoutingCallableString('not_a_real_callable_fn')) + ->toThrow(TypeError::class, 'Variable $x must be of type callable-string') + ; + + $holder = new InlineConfigRoutingHolder(); + expect(fn () => $holder->classString = 'NotARealClass') + ->toThrow(TypeError::class, 'Property InlineConfigRoutingHolder::$classString must be of type class-string') + ; + }); + + test('skips all scalar refinement identifiers when scalars is disabled even if objects is enabled', function () { + TypePHP::setConfig([ + 'inline_vars' => [ + 'properties' => true, + 'scalars' => false, + 'objects' => true, + 'arrays' => false, + 'generics' => false, + 'callables' => false, + ], + ]); + + expect(testInlineRoutingNumber('not-a-number'))->toBe('not-a-number'); + expect(testInlineRoutingLiteralString(123))->toBe(123); + expect(testInlineRoutingTruthyString('0'))->toBe('0'); + expect(testInlineRoutingNonFalsyString('0'))->toBe('0'); + expect(testInlineRoutingFalsey('truthy'))->toBe('truthy'); + expect(testInlineRoutingClassString('NotARealClass'))->toBe('NotARealClass'); + expect(testInlineRoutingInterfaceString(stdClass::class))->toBe(stdClass::class); + expect(testInlineRoutingTraitString(stdClass::class))->toBe(stdClass::class); + expect(testInlineRoutingEnumString(stdClass::class))->toBe(stdClass::class); + expect(testInlineRoutingCallableString('not_a_real_callable_fn'))->toBe('not_a_real_callable_fn'); + }); + }); + + describe('Scalar Generic Refinements (int, int-mask, class-string, key-of)', function () { + test('enforces scalar generics when only scalars is enabled', function () { + TypePHP::setConfig([ + 'inline_vars' => [ + 'properties' => true, + 'scalars' => true, + 'objects' => false, + 'generics' => false, + 'arrays' => false, + 'callables' => false, + ], + ]); + + expect(testInlineRoutingIntRange(5))->toBe(5); + expect(testInlineRoutingIntMask(3))->toBe(3); + expect(testInlineRoutingGenericClassString(RuntimeException::class))->toBe(RuntimeException::class); + expect(testInlineRoutingKeyOf('a'))->toBe('a'); + + expect(fn () => testInlineRoutingIntRange(99)) + ->toThrow(TypeError::class, 'Variable $x must be <= 10') + ; + expect(fn () => testInlineRoutingIntMask(8)) + ->toThrow(TypeError::class, 'Variable $x must be a valid bitmask combination') + ; + expect(fn () => testInlineRoutingGenericClassString(stdClass::class)) + ->toThrow(TypeError::class, 'Variable $x must be a class-string of Throwable') + ; + expect(fn () => testInlineRoutingKeyOf('c')) + ->toThrow(TypeError::class, 'Variable $x must be a key of the specified array shape') + ; + }); + + test('does not strip scalar generic parameters when generics is disabled and objects is enabled', function () { + TypePHP::setConfig([ + 'inline_vars' => [ + 'properties' => true, + 'scalars' => true, + 'objects' => true, + 'generics' => false, + 'arrays' => false, + 'callables' => false, + ], + ]); + + expect(fn () => testInlineRoutingIntRange(99)) + ->toThrow(TypeError::class, 'Variable $x must be <= 10') + ; + expect(fn () => testInlineRoutingIntMask(8)) + ->toThrow(TypeError::class, 'Variable $x must be a valid bitmask combination') + ; + expect(fn () => testInlineRoutingGenericClassString(stdClass::class)) + ->toThrow(TypeError::class, 'Variable $x must be a class-string of Throwable') + ; + expect(fn () => testInlineRoutingKeyOf('c')) + ->toThrow(TypeError::class, 'Variable $x must be a key of the specified array shape') + ; + }); + + test('skips scalar generics when scalars is disabled even if generics is enabled', function () { + TypePHP::setConfig([ + 'inline_vars' => [ + 'properties' => true, + 'scalars' => false, + 'generics' => true, + 'objects' => false, + 'arrays' => false, + 'callables' => false, + ], + ]); + + expect(testInlineRoutingIntRange(99))->toBe(99); + expect(testInlineRoutingIntMask(8))->toBe(8); + expect(testInlineRoutingGenericClassString(stdClass::class))->toBe(stdClass::class); + expect(testInlineRoutingKeyOf('c'))->toBe('c'); + }); + }); + + describe('SpecialTypeResolver Built-in Keyword Recognition', function () { + test('recognizes non-falsy-string and pure-callable as built-in keywords when binding generic instances', function () { + /** @var InlineConfigRoutingGenericBox $box */ + $box = new InlineConfigRoutingGenericBox(); + + $box->set('valid'); + expect($box->value)->toBe('valid'); + + expect(fn () => $box->set('0')) + ->toThrow(TypeError::class, 'must be of type non-falsy-string') + ; + + expect(\TypePHP\Internal\Resolver\SpecialTypeResolver::isBuiltInTypeKeyword('non-falsy-string'))->toBeTrue(); + expect(\TypePHP\Internal\Resolver\SpecialTypeResolver::isBuiltInTypeKeyword('pure-callable'))->toBeTrue(); + expect(\TypePHP\Internal\Resolver\SpecialTypeResolver::isBuiltInTypeKeyword('non-empty-array-list'))->toBeTrue(); + }); + }); +}); From 85ba2edd263b6f1090a88fdaa5a6cf0f4a367895 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sat, 5 Dec 2026 02:29:52 +0800 Subject: [PATCH 15/24] Enhance EliminationSafetyPolicy with new type checks for object generics; update StaticTypeEvaluator and FunctionContractInjector to utilize new checks; add EliminationBox and ObjectGenericReturnEliminationTest for comprehensive testing of elimination safety rules. --- .../Elimination/EliminationSafetyPolicy.php | 105 ++++++- .../Ast/Elimination/StaticTypeEvaluator.php | 7 +- src/Internal/Ast/FunctionContractInjector.php | 1 + tests/Fixtures/Domain/EliminationBox.php | 24 ++ .../ObjectGenericReturnEliminationTest.php | 271 ++++++++++++++++++ 5 files changed, 402 insertions(+), 6 deletions(-) create mode 100644 tests/Fixtures/Domain/EliminationBox.php create mode 100644 tests/TypeChecking/Generics/ObjectGenericReturnEliminationTest.php diff --git a/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php b/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php index c20eba60..385c1a49 100644 --- a/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php +++ b/src/Internal/Ast/Elimination/EliminationSafetyPolicy.php @@ -8,10 +8,19 @@ use PhpParser\Node\Expr\Closure; use PhpParser\Node\Stmt\ClassMethod; use PhpParser\Node\Stmt\Function_; +use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode; use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode; +use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode; +use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeForParameterNode; +use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeNode; use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; +use PHPStan\PhpDocParser\Ast\Type\IntersectionTypeNode; +use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode; +use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode; +use PHPStan\PhpDocParser\Ast\Type\OffsetAccessTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; +use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; /** * Enforces LSP safety rules and runtime state invariants to determine @@ -78,11 +87,8 @@ public static function isReturnEliminationSafe( return false; } - if ($returnTypeNode instanceof GenericTypeNode) { - $baseName = strtolower((string) $returnTypeNode->type); - if (! isset(self::PERMISSIBLE_NON_OBJECT_GENERICS[$baseName])) { - return false; - } + if (self::containsObjectGeneric($returnTypeNode)) { + return false; } if ($classContext === null || $functionNode instanceof Function_ || $functionNode instanceof Closure || $functionNode instanceof ArrowFunction) { @@ -156,4 +162,93 @@ public static function isGeneratorEliminationSafe( return false; } + + /** + * Recursively checks whether a TypeNode contains any object GenericTypeNode + * (e.g. Collection, ?Collection, Collection|null, list>, + * array{c: Collection}) whose runtime WeakMap template bindings must be preserved. + */ + public static function containsObjectGeneric(TypeNode $typeNode): bool + { + while ($typeNode instanceof NullableTypeNode || $typeNode instanceof ArrayTypeNode) { + $typeNode = $typeNode->type; + } + + if ($typeNode instanceof GenericTypeNode) { + $baseName = strtolower((string) $typeNode->type); + if (! isset(self::PERMISSIBLE_NON_OBJECT_GENERICS[$baseName])) { + return true; + } + + foreach ($typeNode->genericTypes as $genericArg) { + if (self::containsObjectGeneric($genericArg)) { + return true; + } + } + + return false; + } + + if ($typeNode instanceof UnionTypeNode || $typeNode instanceof IntersectionTypeNode) { + foreach ($typeNode->types as $member) { + if (self::containsObjectGeneric($member)) { + return true; + } + } + + return false; + } + + if ($typeNode instanceof ArrayShapeNode) { + foreach ($typeNode->items as $item) { + if (self::containsObjectGeneric($item->valueType)) { + return true; + } + } + + if ($typeNode->unsealedType !== null) { + if (self::containsObjectGeneric($typeNode->unsealedType->valueType)) { + return true; + } + + if ($typeNode->unsealedType->keyType !== null && self::containsObjectGeneric($typeNode->unsealedType->keyType)) { + return true; + } + } + + return false; + } + + if ($typeNode instanceof ObjectShapeNode) { + foreach ($typeNode->items as $item) { + if (self::containsObjectGeneric($item->valueType)) { + return true; + } + } + + return false; + } + + if ($typeNode instanceof CallableTypeNode) { + foreach ($typeNode->parameters as $param) { + if (self::containsObjectGeneric($param->type)) { + return true; + } + } + + return self::containsObjectGeneric($typeNode->returnType); + } + + if ($typeNode instanceof ConditionalTypeNode || $typeNode instanceof ConditionalTypeForParameterNode) { + return self::containsObjectGeneric($typeNode->if) + || self::containsObjectGeneric($typeNode->else); + } + + if ($typeNode instanceof OffsetAccessTypeNode) { + return self::containsObjectGeneric($typeNode->type) + || self::containsObjectGeneric($typeNode->offset); + } + + return false; + } } diff --git a/src/Internal/Ast/Elimination/StaticTypeEvaluator.php b/src/Internal/Ast/Elimination/StaticTypeEvaluator.php index 9108d273..781fcb50 100644 --- a/src/Internal/Ast/Elimination/StaticTypeEvaluator.php +++ b/src/Internal/Ast/Elimination/StaticTypeEvaluator.php @@ -76,7 +76,12 @@ public static function satisfies( } } - if ($expr instanceof Variable && \is_string($expr->name) && isset($trustedVariableTypes[$expr->name])) { + if ( + $expr instanceof Variable + && \is_string($expr->name) + && isset($trustedVariableTypes[$expr->name]) + && ! EliminationSafetyPolicy::containsObjectGeneric($typeNode) + ) { $resolvedTarget = $currentFile !== '' ? SpecialTypeResolver::resolveForFile($typeNode, $currentFile, $currentNamespace, false) : $typeNode; diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index a642f74b..6ce8c51a 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -1842,6 +1842,7 @@ public static function inlineVarSubsumesReturn( if ( ! $isEliminationSafe || $targetReturnType === null + || EliminationSafetyPolicy::containsObjectGeneric($targetReturnType) || ! Config::isInlineScalarsEnabled() || ! Config::isInlineArraysEnabled() || ! Config::isInlineObjectsEnabled() diff --git a/tests/Fixtures/Domain/EliminationBox.php b/tests/Fixtures/Domain/EliminationBox.php new file mode 100644 index 00000000..cdef231d --- /dev/null +++ b/tests/Fixtures/Domain/EliminationBox.php @@ -0,0 +1,24 @@ +item = $item; + } +} diff --git a/tests/TypeChecking/Generics/ObjectGenericReturnEliminationTest.php b/tests/TypeChecking/Generics/ObjectGenericReturnEliminationTest.php new file mode 100644 index 00000000..f15a7827 --- /dev/null +++ b/tests/TypeChecking/Generics/ObjectGenericReturnEliminationTest.php @@ -0,0 +1,271 @@ + + */ +function testElimReturnNullableDogBox(EliminationBox $box): ?EliminationBox +{ + return $box; +} + +/** + * @param EliminationBox $box + * + * @return EliminationBox|null + */ +function testElimReturnUnionNullDogBox(EliminationBox $box): ?EliminationBox +{ + return $box; +} + +/** + * @param EliminationBox $box + * + * @return EliminationBox|string + */ +function testElimReturnUnionStringDogBox(EliminationBox $box): EliminationBox|string +{ + return $box; +} + +/** + * @param list $boxes + * + * @return list> + */ +function testElimReturnDogBoxList(array $boxes): array +{ + return $boxes; +} + +/** + * @param EliminationBox[] $boxes + * + * @return EliminationBox[] + */ +function testElimReturnDogBoxTypedArray(array $boxes): array +{ + return $boxes; +} + +/** + * @param EliminationBox $box + * + * @return array{box: ?EliminationBox} + */ +function testElimReturnShapeWithNullableDogBox(EliminationBox $box): array +{ + return ['box' => $box]; +} + +/** + * @param EliminationBox $box + * + * @return list> + */ +function testElimReturnListLiteralWithNullableDogBox(EliminationBox $box): array +{ + return [$box]; +} + +/** + * @return ?EliminationBox + */ +function testElimReturnInlineVarNullableDogBox(mixed $val): ?EliminationBox +{ + /** @var EliminationBox */ + return $val; +} + +/** + * @param EliminationBox $box + * + * @return Generator> + */ +function testElimGeneratorReturnNullableDogBox(EliminationBox $box): Generator +{ + yield 1; + + return $box; +} + +function parseElimTestType(string $typeString): TypeNode +{ + [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); + $tokens = new TokenIterator($lexer->tokenize(DocblockNormalizer::normalize($typeString))); + + return $typeParser->parse($tokens); +} + +describe('Object-Generic Return Check Elimination Safety', function () { + $boxFqcn = EliminationBox::class; + $dogFqcn = Dog::class; + $carBoxLabel = EliminationBox::class . '<' . Car::class . '>'; + + describe('EliminationSafetyPolicy::isReturnEliminationSafe()', function () use ($boxFqcn, $dogFqcn) { + test('rejects nullable, union, and container-wrapped object generics', function () use ($boxFqcn, $dogFqcn) { + $fn = new Function_('dummy'); + + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType("{$boxFqcn}<{$dogFqcn}>")))->toBeFalse(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType("?{$boxFqcn}<{$dogFqcn}>")))->toBeFalse(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType("{$boxFqcn}<{$dogFqcn}>|null")))->toBeFalse(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType("{$boxFqcn}<{$dogFqcn}>|string")))->toBeFalse(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType("list<{$boxFqcn}<{$dogFqcn}>>")))->toBeFalse(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType("array>")))->toBeFalse(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType("{$boxFqcn}<{$dogFqcn}>[]")))->toBeFalse(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType("array{box: {$boxFqcn}<{$dogFqcn}>}")))->toBeFalse(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType("array{box: ?{$boxFqcn}<{$dogFqcn}>}")))->toBeFalse(); + }); + + test('still permits non-generic objects, scalar generics, and non-object-generic collections', function () use ($dogFqcn) { + $fn = new Function_('dummy'); + + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType("?{$dogFqcn}")))->toBeTrue(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType("list<{$dogFqcn}>")))->toBeTrue(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType('list')))->toBeTrue(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType('?int')))->toBeTrue(); + expect(EliminationSafetyPolicy::isReturnEliminationSafe($fn, null, parseElimTestType('int<1, 10>|null')))->toBeTrue(); + }); + }); + + describe('StaticTypeEvaluator::satisfies()', function () use ($boxFqcn, $dogFqcn) { + test('does not prove a trusted raw-class variable satisfies nullable, union, or nested object generics', function () use ($boxFqcn, $dogFqcn) { + $boxVar = new Variable('box'); + $boxesVar = new Variable('boxes'); + $rawBoxTrusted = ['box' => parseElimTestType($boxFqcn)]; + $rawBoxListTrusted = ['boxes' => parseElimTestType("list<{$boxFqcn}>")]; + $rawBoxArrayTrusted = ['boxes' => parseElimTestType("{$boxFqcn}[]")]; + + expect(StaticTypeEvaluator::satisfies($boxVar, parseElimTestType("?{$boxFqcn}<{$dogFqcn}>"), '', $rawBoxTrusted))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($boxVar, parseElimTestType("{$boxFqcn}<{$dogFqcn}>|null"), '', $rawBoxTrusted))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($boxVar, parseElimTestType("{$boxFqcn}<{$dogFqcn}>|string"), '', $rawBoxTrusted))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($boxesVar, parseElimTestType("list<{$boxFqcn}<{$dogFqcn}>>"), '', $rawBoxListTrusted))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($boxesVar, parseElimTestType("{$boxFqcn}<{$dogFqcn}>[]"), '', $rawBoxArrayTrusted))->toBeFalse(); + + $shapeLiteral = new Array_([ + new ArrayItem($boxVar, new String_('box')), + ]); + expect(StaticTypeEvaluator::satisfies($shapeLiteral, parseElimTestType("array{box: ?{$boxFqcn}<{$dogFqcn}>}"), '', $rawBoxTrusted))->toBeFalse(); + + $listLiteral = new Array_([ + new ArrayItem($boxVar), + ]); + expect(StaticTypeEvaluator::satisfies($listLiteral, parseElimTestType("list>"), '', $rawBoxTrusted))->toBeFalse(); + }); + + test('still proves sound non-generic trusted variable returns', function () use ($boxFqcn, $dogFqcn) { + $xVar = new Variable('x'); + + expect(StaticTypeEvaluator::satisfies($xVar, parseElimTestType('?int'), '', ['x' => parseElimTestType('?int')]))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies($xVar, parseElimTestType('int|string'), '', ['x' => parseElimTestType('int|string')]))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies($xVar, parseElimTestType("{$boxFqcn}<{$dogFqcn}>|int"), '', ['x' => parseElimTestType('int')]))->toBeTrue(); + }); + }); + + describe('End-to-End Runtime Enforcement and WeakMap Binding Preservation', function () use ($carBoxLabel) { + test('rejects Box and preserves WeakMap binding on @return ?Box', function () use ($carBoxLabel) { + $carBox = new EliminationBox(); + $carBox->set(new Car()); + + expect(fn () => testElimReturnNullableDogBox($carBox)) + ->toThrow(TypeError::class, $carBoxLabel) + ; + + $unboundBox = new EliminationBox(); + $boundBox = testElimReturnNullableDogBox($unboundBox); + + expect($boundBox)->toBe($unboundBox); + expect(TypePHP::getGenericType($boundBox))->toBe(Dog::class); + expect(fn () => $boundBox->set(new Car())) + ->toThrow(TypeError::class, Dog::class) + ; + }); + + test('rejects Box on union @return Box|null and Box|string', function () use ($carBoxLabel) { + $carBox = new EliminationBox(); + $carBox->set(new Car()); + + expect(fn () => testElimReturnUnionNullDogBox($carBox)) + ->toThrow(TypeError::class, $carBoxLabel) + ; + + expect(fn () => testElimReturnUnionStringDogBox($carBox)) + ->toThrow(TypeError::class, $carBoxLabel) + ; + }); + + test('rejects list> on @return list> and @return Box[]', function () use ($carBoxLabel) { + $carBox = new EliminationBox(); + $carBox->set(new Car()); + + expect(fn () => testElimReturnDogBoxList([$carBox])) + ->toThrow(TypeError::class, $carBoxLabel) + ; + + expect(fn () => testElimReturnDogBoxTypedArray([$carBox])) + ->toThrow(TypeError::class, $carBoxLabel) + ; + }); + + test('rejects Box in array shape and list literals targeting nullable object generics', function () use ($carBoxLabel) { + $carBox = new EliminationBox(); + $carBox->set(new Car()); + + expect(fn () => testElimReturnShapeWithNullableDogBox($carBox)) + ->toThrow(TypeError::class, $carBoxLabel) + ; + + expect(fn () => testElimReturnListLiteralWithNullableDogBox($carBox)) + ->toThrow(TypeError::class, $carBoxLabel) + ; + }); + + test('does not let inline @var Box subsume @return ?Box', function () use ($carBoxLabel) { + $carBox = new EliminationBox(); + $carBox->set(new Car()); + + expect(fn () => testElimReturnInlineVarNullableDogBox($carBox)) + ->toThrow(TypeError::class, $carBoxLabel) + ; + }); + + test('does not eliminate generator TReturn check on Generator>', function () use ($carBoxLabel) { + $carBox = new EliminationBox(); + $carBox->set(new Car()); + + expect(function () use ($carBox) { + $gen = testElimGeneratorReturnNullableDogBox($carBox); + iterator_to_array($gen); + $gen->getReturn(); + })->toThrow(TypeError::class, $carBoxLabel); + + $unboundBox = new EliminationBox(); + $gen = testElimGeneratorReturnNullableDogBox($unboundBox); + iterator_to_array($gen); + $boundBox = $gen->getReturn(); + + expect($boundBox)->toBe($unboundBox); + expect(TypePHP::getGenericType($boundBox))->toBe(Dog::class); + }); + }); +}); From a8df960f45946351f657ffe91da65aaf32ffa631 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sat, 5 Dec 2026 12:53:13 +0800 Subject: [PATCH 16/24] Refactor ReturnChecker and RuntimeTypeChecker to utilize IterableWrapper for traversable type checks; add new IterableWrapper methods for enhanced type validation; introduce Nullable and Union Iterable Return tests for comprehensive coverage. --- src/Internal/Checker/ReturnChecker.php | 40 +-- src/Internal/RuntimeTypeChecker.php | 30 +- src/Internal/Wrapper/IterableWrapper.php | 195 ++++++++++-- .../NullableAndUnionIterableReturnTest.php | 295 ++++++++++++++++++ 4 files changed, 486 insertions(+), 74 deletions(-) create mode 100644 tests/TypeChecking/CallablesAndIterators/NullableAndUnionIterableReturnTest.php diff --git a/src/Internal/Checker/ReturnChecker.php b/src/Internal/Checker/ReturnChecker.php index eb7cfbb4..b9c8c3f4 100644 --- a/src/Internal/Checker/ReturnChecker.php +++ b/src/Internal/Checker/ReturnChecker.php @@ -19,6 +19,7 @@ use TypePHP\Internal\Util\Config; use TypePHP\Internal\Validator\TypeValidatorRegistry; use TypePHP\Internal\Wrapper\CallableWrapper; +use TypePHP\Internal\Wrapper\IterableWrapper; /** * Evaluates function and method return contracts, including dynamic `@method` returns @@ -289,17 +290,8 @@ private static function handleMagicPropertyRead( return ErrorFactory::createError($msg); } - if ($value instanceof Traversable) { - $baseName = ''; - if ($typeNode instanceof IdentifierTypeNode) { - $baseName = strtolower(ltrim($typeNode->name, '\\')); - } elseif ($typeNode instanceof GenericTypeNode) { - $baseName = strtolower(ltrim((string) $typeNode->type, '\\')); - } - - if (isset(self::GENERIC_ITERABLES[$baseName])) { - return $wrapIterableCallback($effectiveFunction, 'return', $value); - } + if ($value instanceof Traversable && IterableWrapper::containsTraversableIterable($typeNode)) { + return $wrapIterableCallback($effectiveFunction, 'return', $value, $thisObj, $typeNode); } return $value; @@ -422,17 +414,8 @@ private static function evaluateReturn( return ErrorFactory::createError($function . '(): ' . $err->getMessage()); } - if ($value instanceof Traversable) { - $baseName = ''; - if ($resolvedType instanceof IdentifierTypeNode) { - $baseName = strtolower(ltrim($resolvedType->name, '\\')); - } elseif ($resolvedType instanceof GenericTypeNode) { - $baseName = strtolower(ltrim((string) $resolvedType->type, '\\')); - } - - if (isset(self::GENERIC_ITERABLES[$baseName])) { - return $wrapIterableCallback($function, 'return', $value); - } + if ($value instanceof Traversable && IterableWrapper::containsTraversableIterable($resolvedType)) { + return $wrapIterableCallback($function, 'return', $value, $thisObj, $resolvedType); } return $value; @@ -579,17 +562,8 @@ private static function evaluateReturn( return CallableWrapper::wrapTypeNode($resolvedType, $value, $function . '(): Return value', $registry); } - if ($value instanceof Traversable) { - $baseName = ''; - if ($resolvedType instanceof IdentifierTypeNode) { - $baseName = strtolower(ltrim($resolvedType->name, '\\')); - } elseif ($resolvedType instanceof GenericTypeNode) { - $baseName = strtolower(ltrim((string) $resolvedType->type, '\\')); - } - - if (isset(self::GENERIC_ITERABLES[$baseName])) { - return $wrapIterableCallback($function, 'return', $value); - } + if ($value instanceof Traversable && IterableWrapper::containsTraversableIterable($resolvedType)) { + return $wrapIterableCallback($function, 'return', $value, $thisObj, $resolvedType); } return $value; diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index 5aa10566..a8680d7b 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -2502,14 +2502,7 @@ public static function checkReturn(string $function, mixed $value, object|string } } - $isTraversableIterable = false; - if ($resolvedType instanceof IdentifierTypeNode) { - $baseName = strtolower(ltrim($resolvedType->name, '\\')); - $isTraversableIterable = isset(ReturnChecker::GENERIC_ITERABLES[$baseName]); - } elseif ($resolvedType instanceof GenericTypeNode) { - $baseName = strtolower(ltrim((string) $resolvedType->type, '\\')); - $isTraversableIterable = isset(ReturnChecker::GENERIC_ITERABLES[$baseName]); - } + $isTraversableIterable = IterableWrapper::containsTraversableIterable($resolvedType); if (! $isTraversableIterable && isset(CallerBoundaryResolver::$nonBypassCalleeCache[$effectiveFunction])) { [$op, $extra] = self::compileSimpleReturnOp($resolvedType); @@ -2544,7 +2537,7 @@ public static function checkReturn(string $function, mixed $value, object|string } if ($isTraversableIterable && $value instanceof Traversable) { - return self::wrapIterable($effectiveFunction, 'return', $value); + return self::wrapIterable($effectiveFunction, 'return', $value, $thisObj, $resolvedType); } return $value; @@ -2955,8 +2948,13 @@ public static function wrapCallable(string $function, string $paramName, mixed $ /** * Wraps an iterable or generator parameter to lazily validate items during iteration. */ - public static function wrapIterable(string $function, string $paramName, mixed $iterable, object|string|null $thisOrClass = null): mixed - { + public static function wrapIterable( + string $function, + string $paramName, + mixed $iterable, + object|string|null $thisOrClass = null, + ?TypeNode $resolvedTypeNode = null + ): mixed { if (! self::$isEnabled || (\is_array($iterable) && $paramName !== 'return') || ! is_iterable($iterable)) { return $iterable; } @@ -2968,7 +2966,15 @@ public static function wrapIterable(string $function, string $paramName, mixed $ return $iterable; } - return IterableWrapper::wrap($function, $paramName, $iterable, self::$registry ??= new TypeValidatorRegistry(), $thisOrClass); + $registry = self::$registry ??= new TypeValidatorRegistry(); + + if ($resolvedTypeNode !== null && $iterable instanceof Traversable) { + $prefix = ($paramName === 'return') ? "$effectiveFunction(): Return iterator" : "$effectiveFunction(): Iterator \$$paramName"; + + return IterableWrapper::wrapTypeNode($resolvedTypeNode, $iterable, $prefix, $registry, $effectiveFunction); + } + + return IterableWrapper::wrap($function, $paramName, $iterable, $registry, $thisOrClass); } /** diff --git a/src/Internal/Wrapper/IterableWrapper.php b/src/Internal/Wrapper/IterableWrapper.php index ab7b26ef..125e5c85 100644 --- a/src/Internal/Wrapper/IterableWrapper.php +++ b/src/Internal/Wrapper/IterableWrapper.php @@ -5,12 +5,14 @@ namespace TypePHP\Internal\Wrapper; use Generator; +use Iterator; use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode; use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; +use Traversable; use TypePHP\Exception\TypeError as TypePHPTypeError; use TypePHP\Internal\Checker\ConditionalChecker; use TypePHP\Internal\Diagnostic\ErrorFactory; @@ -31,6 +33,13 @@ */ final class IterableWrapper { + private const STANDARD_ITERABLES = [ + 'iterable' => true, + 'traversable' => true, + 'iterator' => true, + 'generator' => true, + ]; + /** * @var array or iterable|false). + */ + public static function containsTraversableIterable(TypeNode $typeNode): bool + { + while ($typeNode instanceof NullableTypeNode) { + $typeNode = $typeNode->type; + } + + if ($typeNode instanceof IdentifierTypeNode) { + return isset(self::STANDARD_ITERABLES[strtolower(ltrim($typeNode->name, '\\'))]); + } + + if ($typeNode instanceof GenericTypeNode) { + return isset(self::STANDARD_ITERABLES[strtolower(ltrim((string) $typeNode->type, '\\'))]); + } + + if ($typeNode instanceof UnionTypeNode) { + foreach ($typeNode->types as $member) { + if (self::containsTraversableIterable($member)) { + return true; + } + } + } + + return false; + } + + /** + * Wraps a Traversable or Generator using an already-resolved TypeNode AST + * (preserving resolved class/method generics, conditionals, aliases, and magic @method contracts). + * + * @param array $aliases + */ + public static function wrapTypeNode( + TypeNode $typeNode, + mixed $iterable, + string $prefix, + TypeValidatorRegistry $registry, + string $function = '', + array $aliases = [] + ): mixed { + if (! ($iterable instanceof Traversable)) { + return $iterable; + } + + $traversableNode = self::extractTraversableTypeNode($typeNode, $iterable, $aliases); + if ($traversableNode === null) { + return $iterable; + } + + [$keyTypeNode, $itemTypeNode] = self::extractKeyAndItemTypeNodes($traversableNode, $aliases); + if (self::isUnconstrainedKey($keyTypeNode) && self::isUnconstrained($itemTypeNode)) { + return $iterable; + } + + $typeCheckCallback = self::createValidationCallback($registry, $keyTypeNode, $itemTypeNode, $prefix, $function); + + if (! ($iterable instanceof Generator)) { + return new IteratorProxy($iterable, $typeCheckCallback); + } + + return self::wrapGenerator($iterable, $typeCheckCallback); + } + /** * Wraps Traversable iterators and Generators to lazily validate keys and values during iteration. */ @@ -183,36 +258,10 @@ private static function resolveKeyAndItemTypes( } } - while ($typeNode instanceof NullableTypeNode) { - $typeNode = $typeNode->type; - } - - if ($typeNode instanceof UnionTypeNode) { - $nonNullNode = null; - $nonNullCount = 0; - foreach ($typeNode->types as $member) { - if ($member instanceof IdentifierTypeNode && strtolower($member->name) === 'null') { - continue; - } - $nonNullCount++; - $nonNullNode = $member; - } - if ($nonNullCount === 1 && $nonNullNode !== null) { - $typeNode = $nonNullNode; - } - } - - $baseName = ''; - if ($typeNode instanceof IdentifierTypeNode) { - $baseName = strtolower(ltrim($typeNode->name, '\\')); - } elseif ($typeNode instanceof GenericTypeNode) { - $baseName = strtolower(ltrim((string) $typeNode->type, '\\')); - } - $result = null; - $standardIterables = ['iterable', 'traversable', 'iterator', 'generator']; - if (\in_array($baseName, $standardIterables, strict: true)) { - [$keyTypeNode, $itemTypeNode] = self::extractKeyAndItemTypeNodes($typeNode, $plan['aliases']); + $traversableNode = self::extractTraversableTypeNode($typeNode, null, $plan['aliases']); + if ($traversableNode !== null) { + [$keyTypeNode, $itemTypeNode] = self::extractKeyAndItemTypeNodes($traversableNode, $plan['aliases']); if (! self::isUnconstrainedKey($keyTypeNode) || ! self::isUnconstrained($itemTypeNode)) { $result = [$keyTypeNode, $itemTypeNode]; } @@ -414,4 +463,92 @@ private static function wrapGenerator(iterable $iterable, \Closure $typeCheckCal yield $key => $value; } } + + /** + * Extracts the unique matching Traversable/iterable TypeNode from a direct, nullable, or union TypeNode. + * + * @param array $aliases + */ + private static function extractTraversableTypeNode(TypeNode $typeNode, mixed $iterable = null, array $aliases = []): ?TypeNode + { + /** @var list $matches */ + $matches = []; + self::collectTraversableBranches($typeNode, $iterable, $aliases, $matches); + + if (\count($matches) === 1) { + return $matches[0]; + } + + if (\count($matches) > 1) { + [$firstKey, $firstItem] = self::extractKeyAndItemTypeNodes($matches[0], $aliases); + $firstKeyStr = $firstKey !== null ? (string) $firstKey : ''; + $firstItemStr = $firstItem !== null ? (string) $firstItem : ''; + + for ($i = 1, $count = \count($matches); $i < $count; $i++) { + [$k, $v] = self::extractKeyAndItemTypeNodes($matches[$i], $aliases); + if (($k !== null ? (string) $k : '') !== $firstKeyStr || ($v !== null ? (string) $v : '') !== $firstItemStr) { + return null; + } + } + + return $matches[0]; + } + + return null; + } + + /** + * @param array $aliases + * @param list $matches + */ + private static function collectTraversableBranches( + TypeNode $typeNode, + mixed $iterable, + array $aliases, + array &$matches + ): void { + while ($typeNode instanceof NullableTypeNode) { + $typeNode = $typeNode->type; + } + + if ($typeNode instanceof IdentifierTypeNode && isset($aliases[$typeNode->name])) { + $typeNode = $aliases[$typeNode->name]; + while ($typeNode instanceof NullableTypeNode) { + $typeNode = $typeNode->type; + } + } + + if ($typeNode instanceof UnionTypeNode) { + foreach ($typeNode->types as $member) { + self::collectTraversableBranches($member, $iterable, $aliases, $matches); + } + + return; + } + + $baseName = ''; + if ($typeNode instanceof IdentifierTypeNode) { + $baseName = strtolower(ltrim($typeNode->name, '\\')); + } elseif ($typeNode instanceof GenericTypeNode) { + $baseName = strtolower(ltrim((string) $typeNode->type, '\\')); + } + + if ($baseName !== '' && isset(self::STANDARD_ITERABLES[$baseName]) && self::traversableBranchMatchesValue($baseName, $iterable)) { + $matches[] = $typeNode; + } + } + + private static function traversableBranchMatchesValue(string $baseName, mixed $iterable): bool + { + if (! ($iterable instanceof Traversable)) { + return true; + } + + return match ($baseName) { + 'iterable', 'traversable' => true, + 'iterator' => $iterable instanceof Iterator, + 'generator' => $iterable instanceof Generator, + default => false, + }; + } } diff --git a/tests/TypeChecking/CallablesAndIterators/NullableAndUnionIterableReturnTest.php b/tests/TypeChecking/CallablesAndIterators/NullableAndUnionIterableReturnTest.php new file mode 100644 index 00000000..e01d08fe --- /dev/null +++ b/tests/TypeChecking/CallablesAndIterators/NullableAndUnionIterableReturnTest.php @@ -0,0 +1,295 @@ + + */ +function testReturnNullableIterable(mixed $val): ?iterable +{ + return $val; +} + +/** + * @return ?Traversable + */ +function testReturnNullableTraversable(mixed $val): ?Traversable +{ + return $val; +} + +/** + * @return ?Iterator + */ +function testReturnNullableIterator(mixed $val): ?Iterator +{ + return $val; +} + +/** + * @return ?Generator + */ +function testReturnNullableGenerator(mixed $val): ?Generator +{ + return $val; +} + +/** + * @return iterable|null + */ +function testReturnUnionNullIterable(mixed $val): ?iterable +{ + return $val; +} + +/** + * @return iterable|false + */ +function testReturnUnionFalseIterable(mixed $val): iterable|false +{ + return $val; +} + +/** + * @return Traversable|string + */ +function testReturnUnionStringTraversable(mixed $val): Traversable|string +{ + return $val; +} + +/** + * @return Generator|array + */ +function testReturnUnionGeneratorOrArray(mixed $val): Generator|array +{ + return $val; +} + +/** + * @return ($asIterable is true ? iterable : string) + */ +function testReturnConditionalIterable(bool $asIterable, mixed $val): iterable|string +{ + return $val; +} + +/** + * @template T + */ +final class GenericIterableReturnBox +{ + /** + * @param T $seed + */ + public function __construct(public mixed $seed) + { + } + + /** + * @return iterable + */ + public function stream(mixed $val): iterable + { + return $val; + } + + /** + * @return ?iterable + */ + public function streamNullable(mixed $val): ?iterable + { + return $val; + } +} + +/** + * @phpstan-type NullableIntStream ?iterable + */ +final class AliasIterableReturnHolder +{ + /** + * @return NullableIntStream + */ + public function stream(mixed $val): ?iterable + { + return $val; + } +} + +/** + * @method ?iterable streamNumbers(mixed $val) + */ +final class MagicIterableReturnCaller +{ + /** + * @param array $args + */ + public function __call(string $name, array $args): mixed + { + return $args[0] ?? null; + } +} + +describe('Nullable and Union Iterable / Generator Return Wrapping', function () { + describe('Nullable Iterable Returns (?iterable, ?Traversable, ?Iterator, ?Generator)', function () { + test('accepts null and valid iterables while lazily validating invalid Traversable values on @return ?iterable (cold and warm)', function () { + expect(testReturnNullableIterable(null))->toBeNull(); + expect(testReturnNullableIterable([1, 2]))->toBe([1, 2]); + expect(iterator_to_array(testReturnNullableIterable(new ArrayIterator([1, 2]))))->toBe([1, 2]); + + expect(fn () => testReturnNullableIterable(['bad'])) + ->toThrow(TypeError::class, 'must be of type int') + ; + + $wrapped = testReturnNullableIterable(new ArrayIterator([1, 'bad'])); + expect(fn () => iterator_to_array($wrapped)) + ->toThrow(TypeError::class, 'Return iterator value must be of type int') + ; + }); + + test('lazily validates keys and values on @return ?Traversable and @return ?Iterator', function () { + expect(testReturnNullableTraversable(null))->toBeNull(); + expect(iterator_to_array(testReturnNullableTraversable(new ArrayIterator(['a' => 1]))))->toBe(['a' => 1]); + + $badKey = testReturnNullableTraversable(new ArrayIterator([0 => 1])); + expect(fn () => iterator_to_array($badKey)) + ->toThrow(TypeError::class, 'Return iterator key must be of type string') + ; + + $badVal = testReturnNullableTraversable(new ArrayIterator(['a' => 'nope'])); + expect(fn () => iterator_to_array($badVal)) + ->toThrow(TypeError::class, 'Return iterator value must be of type int') + ; + + expect(testReturnNullableIterator(null))->toBeNull(); + $badIter = testReturnNullableIterator(new ArrayIterator(['nope'])); + expect(fn () => iterator_to_array($badIter)) + ->toThrow(TypeError::class, 'Return iterator value must be of type int') + ; + }); + + test('lazily validates yielded keys and values on @return ?Generator', function () { + expect(testReturnNullableGenerator(null))->toBeNull(); + + $validGen = (static function (): Generator { + yield 'ok' => 42; + })(); + expect(iterator_to_array(testReturnNullableGenerator($validGen)))->toBe(['ok' => 42]); + + $badKeyGen = (static function (): Generator { + yield 0 => 42; + })(); + $wrappedBadKey = testReturnNullableGenerator($badKeyGen); + expect(fn () => iterator_to_array($wrappedBadKey)) + ->toThrow(TypeError::class, 'Return iterator key must be of type string') + ; + + $badValGen = (static function (): Generator { + yield 'ok' => 'nope'; + })(); + $wrappedBadVal = testReturnNullableGenerator($badValGen); + expect(fn () => iterator_to_array($wrappedBadVal)) + ->toThrow(TypeError::class, 'Return iterator value must be of type int') + ; + }); + }); + + describe('Union Iterable Returns (|null, |false, |string, |array)', function () { + test('lazily validates Traversable on @return iterable|null (cold and warm)', function () { + expect(testReturnUnionNullIterable(null))->toBeNull(); + expect(iterator_to_array(testReturnUnionNullIterable(new ArrayIterator([10, 20]))))->toBe([10, 20]); + + $wrapped = testReturnUnionNullIterable(new ArrayIterator(['bad'])); + expect(fn () => iterator_to_array($wrapped)) + ->toThrow(TypeError::class, 'Return iterator value must be of type int') + ; + }); + + test('lazily validates keys and values on @return iterable|false', function () { + expect(testReturnUnionFalseIterable(false))->toBeFalse(); + expect(iterator_to_array(testReturnUnionFalseIterable(new ArrayIterator(['k' => 1]))))->toBe(['k' => 1]); + + $badKey = testReturnUnionFalseIterable(new ArrayIterator([0 => 1])); + expect(fn () => iterator_to_array($badKey)) + ->toThrow(TypeError::class, 'Return iterator key must be of type string') + ; + + $badVal = testReturnUnionFalseIterable(new ArrayIterator(['k' => 'bad'])); + expect(fn () => iterator_to_array($badVal)) + ->toThrow(TypeError::class, 'Return iterator value must be of type int') + ; + }); + + test('lazily validates Traversable on @return Traversable|string and Generator on @return Generator|array', function () { + expect(testReturnUnionStringTraversable('fallback'))->toBe('fallback'); + expect(iterator_to_array(testReturnUnionStringTraversable(new ArrayIterator([1, 2]))))->toBe([1, 2]); + + $badTrav = testReturnUnionStringTraversable(new ArrayIterator(['bad'])); + expect(fn () => iterator_to_array($badTrav)) + ->toThrow(TypeError::class, 'Return iterator value must be of type int') + ; + + expect(testReturnUnionGeneratorOrArray([1, 2]))->toBe([1, 2]); + $badGen = (static function (): Generator { + yield 'bad'; + })(); + $wrappedGen = testReturnUnionGeneratorOrArray($badGen); + expect(fn () => iterator_to_array($wrappedGen)) + ->toThrow(TypeError::class, 'Return iterator value must be of type int') + ; + }); + }); + + describe('Generic, Conditional, Alias, and Magic @method Iterable Returns', function () { + test('lazily validates @return iterable and @return ?iterable on generic class instances', function () { + $box = new GenericIterableReturnBox(1); + + expect(iterator_to_array($box->stream(new ArrayIterator([1, 2]))))->toBe([1, 2]); + expect($box->streamNullable(null))->toBeNull(); + expect(iterator_to_array($box->streamNullable(new ArrayIterator([3, 4]))))->toBe([3, 4]); + + $badStream = $box->stream(new ArrayIterator(['not-an-int'])); + expect(fn () => iterator_to_array($badStream)) + ->toThrow(TypeError::class, 'Return iterator value must be of type int') + ; + + $badNullableStream = $box->streamNullable(new ArrayIterator(['not-an-int'])); + expect(fn () => iterator_to_array($badNullableStream)) + ->toThrow(TypeError::class, 'Return iterator value must be of type int') + ; + }); + + test('lazily validates conditional return resolving to iterable', function () { + expect(testReturnConditionalIterable(false, 'text'))->toBe('text'); + expect(iterator_to_array(testReturnConditionalIterable(true, new ArrayIterator([1, 2]))))->toBe([1, 2]); + + $badCond = testReturnConditionalIterable(true, new ArrayIterator(['not-an-int'])); + expect(fn () => iterator_to_array($badCond)) + ->toThrow(TypeError::class, 'Return iterator value must be of type int') + ; + }); + + test('lazily validates type alias resolving to ?iterable', function () { + $holder = new AliasIterableReturnHolder(); + expect($holder->stream(null))->toBeNull(); + expect(iterator_to_array($holder->stream(new ArrayIterator([1, 2]))))->toBe([1, 2]); + + $badAlias = $holder->stream(new ArrayIterator(['not-an-int'])); + expect(fn () => iterator_to_array($badAlias)) + ->toThrow(TypeError::class, 'Return iterator value must be of type int') + ; + }); + + test('lazily validates magic @method returning ?iterable', function () { + $caller = new MagicIterableReturnCaller(); + expect($caller->streamNumbers(null))->toBeNull(); + expect(iterator_to_array($caller->streamNumbers(new ArrayIterator([1, 2]))))->toBe([1, 2]); + + $badMagic = $caller->streamNumbers(new ArrayIterator(['not-an-int'])); + expect(fn () => iterator_to_array($badMagic)) + ->toThrow(TypeError::class, 'Return iterator value must be of type int') + ; + }); + }); +}); From bb27a0832e479ee6cd421d530f552acf6f2e51b4 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sat, 5 Dec 2026 13:15:59 +0800 Subject: [PATCH 17/24] Enhance UnionValidator with improved discriminator checks and add comprehensive tests for discriminated unions, including boolean, null, multi-field, and enum discriminators. --- src/Internal/Validator/UnionValidator.php | 279 +++++++++++++++--- .../DiscriminatedUnionErrorTest.php | 189 ++++++++++++ 2 files changed, 429 insertions(+), 39 deletions(-) create mode 100644 tests/TypeChecking/ArraysAndShapes/DiscriminatedUnionErrorTest.php diff --git a/src/Internal/Validator/UnionValidator.php b/src/Internal/Validator/UnionValidator.php index fb6e1af9..06395ad1 100644 --- a/src/Internal/Validator/UnionValidator.php +++ b/src/Internal/Validator/UnionValidator.php @@ -5,18 +5,23 @@ namespace TypePHP\Internal\Validator; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprFalseNode; +use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprFloatNode; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprNullNode; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprTrueNode; +use PHPStan\PhpDocParser\Ast\ConstExpr\ConstFetchNode; use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode; use PHPStan\PhpDocParser\Ast\Type\ConstTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; -use Stringable; +use ReflectionClass; +use ReflectionProperty; +use Throwable; use Traversable; +use TypePHP\Internal\Diagnostic\DebugLog; use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Diagnostic\TypeFormatter; @@ -208,69 +213,265 @@ private static function extractErrorPathDepth(string $message, string $context): } /** - * Inspects a type branch to see if it defines a discriminator field and whether the input value matches it. + * Inspects a type branch to see if it defines literal discriminator fields and whether the input value matches all of them. * * @return array{hasDiscriminator: bool, isMatched: bool} */ private static function checkDiscriminatorStatus(mixed $value, TypeNode $type): array { if (\is_array($value) && $type instanceof ArrayShapeNode) { - foreach ($type->items as $item) { - if ($item->valueType instanceof ConstTypeNode) { - $key = null; - if ($item->keyName instanceof ConstExprStringNode) { - $key = $item->keyName->value; - } elseif ($item->keyName instanceof IdentifierTypeNode) { - $key = $item->keyName->name; - } elseif ($item->keyName instanceof ConstExprIntegerNode) { - $key = (int) $item->keyName->value; - } + $foundAnyPresentKey = false; + $allMatched = true; + $nextAutoIndex = 0; - if ($key !== null) { - $expectedVal = (string) $item->valueType->constExpr; - $expectedVal = trim($expectedVal, '\'"'); - - if (isset($value[$key])) { - $actualVal = $value[$key]; - $actualStr = \is_scalar($actualVal) || $actualVal instanceof Stringable ? (string) $actualVal : null; + foreach ($type->items as $item) { + $key = self::extractArrayShapeKey($item->keyName, $nextAutoIndex); + if ($item->optional || $key === null) { + continue; + } - if ($actualStr === $expectedVal) { - return ['hasDiscriminator' => true, 'isMatched' => true]; - } + [$isLiteral, $expectedVal] = self::extractDiscriminatorLiteral($item->valueType); + if (! $isLiteral) { + continue; + } - return ['hasDiscriminator' => true, 'isMatched' => false]; - } + if (\array_key_exists($key, $value)) { + $foundAnyPresentKey = true; + if (! self::discriminatorValueMatches($value[$key], $expectedVal)) { + $allMatched = false; } + } else { + $allMatched = false; } } + + if ($foundAnyPresentKey) { + return ['hasDiscriminator' => true, 'isMatched' => $allMatched]; + } } if (\is_object($value) && $type instanceof ObjectShapeNode) { + $foundAnyPresentProp = false; + $allMatched = true; + foreach ($type->items as $item) { - if ($item->valueType instanceof ConstTypeNode) { - $prop = (string) $item->keyName; - $expectedVal = (string) $item->valueType->constExpr; - $expectedVal = trim($expectedVal, '\'"'); - - // @phpstan-ignore property.dynamicName - if (isset($value->$prop)) { - // @phpstan-ignore property.dynamicName - $actualVal = $value->$prop; - $actualStr = \is_scalar($actualVal) || $actualVal instanceof Stringable ? (string) $actualVal : null; - - if ($actualStr === $expectedVal) { - return ['hasDiscriminator' => true, 'isMatched' => true]; - } + if ($item->optional) { + continue; + } - return ['hasDiscriminator' => true, 'isMatched' => false]; + [$isLiteral, $expectedVal] = self::extractDiscriminatorLiteral($item->valueType); + if (! $isLiteral) { + continue; + } + + $prop = self::extractObjectShapeKey($item->keyName); + if ($prop === '') { + continue; + } + + [$exists, $actualVal] = self::readObjectPropertyForDiscriminator($value, $prop); + if ($exists) { + $foundAnyPresentProp = true; + if (! self::discriminatorValueMatches($actualVal, $expectedVal)) { + $allMatched = false; } + } else { + $allMatched = false; } } + + if ($foundAnyPresentProp) { + return ['hasDiscriminator' => true, 'isMatched' => $allMatched]; + } } return ['hasDiscriminator' => false, 'isMatched' => false]; } + /** + * Extracts a concrete literal value from a ConstTypeNode or true/false/null IdentifierTypeNode. + * + * @return array{0: bool, 1: mixed} + */ + private static function extractDiscriminatorLiteral(TypeNode $type): array + { + if ($type instanceof IdentifierTypeNode) { + return match (strtolower($type->name)) { + 'true' => [true, true], + 'false' => [true, false], + 'null' => [true, null], + default => [false, null], + }; + } + + if (! ($type instanceof ConstTypeNode)) { + return [false, null]; + } + + $constExpr = $type->constExpr; + + if ($constExpr instanceof ConstExprStringNode) { + return [true, $constExpr->value]; + } + + if ($constExpr instanceof ConstExprIntegerNode) { + return [true, (int) $constExpr->value]; + } + + if ($constExpr instanceof ConstExprFloatNode) { + return [true, (float) $constExpr->value]; + } + + if ($constExpr instanceof ConstExprTrueNode) { + return [true, true]; + } + + if ($constExpr instanceof ConstExprFalseNode) { + return [true, false]; + } + + if ($constExpr instanceof ConstExprNullNode) { + return [true, null]; + } + + if ($constExpr instanceof ConstFetchNode) { + return self::resolveConstantDiscriminatorValue($constExpr->className, $constExpr->name); + } + + return [false, null]; + } + + /** + * Resolves a single class, interface, enum, or global constant discriminator value. + * + * @return array{0: bool, 1: mixed} + */ + private static function resolveConstantDiscriminatorValue(string $className, string $constName): array + { + if ($constName === '' || str_contains($constName, '*')) { + return [false, null]; + } + + if ($className !== '') { + $lowerClass = strtolower($className); + if ($lowerClass === 'self' || $lowerClass === 'static' || $lowerClass === 'parent' || $lowerClass === '$this') { + return [false, null]; + } + + if ( + ClassNameValidator::isValid($className) + && ( + class_exists($className, false) + || class_exists($className) + || interface_exists($className, false) + || interface_exists($className) + || enum_exists($className, false) + || enum_exists($className) + ) + ) { + try { + /** @var class-string $className */ + $refClass = new ReflectionClass($className); + if ($refClass->hasConstant($constName)) { + return [true, $refClass->getConstant($constName)]; + } + } catch (Throwable $e) { + DebugLog::swallowed($e); // @codeCoverageIgnore + } + } + + return [false, null]; + } + + if (\defined($constName)) { + return [true, \constant($constName)]; + } + + return [false, null]; + } + + private static function discriminatorValueMatches(mixed $actual, mixed $expected): bool + { + if (\is_float($expected)) { + return (\is_float($actual) || \is_int($actual)) && abs((float) $actual - $expected) <= 1e-9; + } + + return $actual === $expected; + } + + private static function extractArrayShapeKey( + ConstExprIntegerNode|ConstExprStringNode|ConstFetchNode|IdentifierTypeNode|null $keyName, + int &$nextAutoIndex + ): string|int|null { + if ($keyName instanceof ConstExprStringNode) { + return $keyName->value; + } + + if ($keyName instanceof IdentifierTypeNode) { + return $keyName->name; + } + + if ($keyName instanceof ConstExprIntegerNode) { + $key = (int) $keyName->value; + $nextAutoIndex = max($nextAutoIndex, $key + 1); + + return $key; + } + + if ($keyName === null) { + $key = $nextAutoIndex; + $nextAutoIndex++; + + return $key; + } + + return null; + } + + private static function extractObjectShapeKey(ConstExprStringNode|IdentifierTypeNode $keyName): string + { + if ($keyName instanceof ConstExprStringNode) { + return $keyName->value; + } + + return $keyName->name; + } + + /** + * Reads an object property value safely, distinguishing null properties from missing/uninitialized ones. + * + * @return array{0: bool, 1: mixed} + */ + private static function readObjectPropertyForDiscriminator(object $value, string $prop): array + { + if ($value instanceof \stdClass) { + if (property_exists($value, $prop)) { + return [true, $value->$prop]; + } + + return [false, null]; + } + + // @phpstan-ignore property.dynamicName + if (isset($value->$prop)) { + // @phpstan-ignore property.dynamicName + return [true, $value->$prop]; + } + + if (property_exists($value, $prop)) { + try { + $refProp = new ReflectionProperty($value, $prop); + if ($refProp->isInitialized($value)) { + return [true, $refProp->getValue($value)]; + } + } catch (Throwable $e) { + DebugLog::swallowed($e); // @codeCoverageIgnore + } + } + + return [false, null]; + } + /** * @return array{ * hasMixed: bool, diff --git a/tests/TypeChecking/ArraysAndShapes/DiscriminatedUnionErrorTest.php b/tests/TypeChecking/ArraysAndShapes/DiscriminatedUnionErrorTest.php new file mode 100644 index 00000000..6bb8f27c --- /dev/null +++ b/tests/TypeChecking/ArraysAndShapes/DiscriminatedUnionErrorTest.php @@ -0,0 +1,189 @@ + true, 'data' => 42]); + testBoolDiscriminatedArray(['ok' => false, 'error' => 'failed']); + + expect(fn () => testBoolDiscriminatedArray(['ok' => false, 'error' => 123])) + ->toThrow(TypeError::class, "Argument \$result['error'] must be of type string") + ; + + expect(fn () => testBoolDiscriminatedArray(['ok' => true, 'data' => 'bad'])) + ->toThrow(TypeError::class, "Argument \$result['data'] must be of type int") + ; + }); + + test('reports the matched false-branch error on object shapes', function () { + testBoolDiscriminatedObject((object) ['ok' => true, 'data' => 42]); + testBoolDiscriminatedObject((object) ['ok' => false, 'error' => 'failed']); + + expect(fn () => testBoolDiscriminatedObject((object) ['ok' => false, 'error' => 123])) + ->toThrow(TypeError::class, 'Argument $result->error must be of type string') + ; + + expect(fn () => testBoolDiscriminatedObject((object) ['ok' => true, 'data' => 'bad'])) + ->toThrow(TypeError::class, 'Argument $result->data must be of type int') + ; + }); + + test('handles explicit ConstTypeNode(ConstExprTrueNode / ConstExprFalseNode / ConstExprNullNode) AST nodes', function () { + $registry = new TypeValidatorRegistry(); + + $boolUnion = new UnionTypeNode([ + ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new IdentifierTypeNode('ok'), false, new ConstTypeNode(new ConstExprTrueNode())), + new ArrayShapeItemNode(new IdentifierTypeNode('data'), false, new IdentifierTypeNode('int')), + ]), + ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new IdentifierTypeNode('ok'), false, new ConstTypeNode(new ConstExprFalseNode())), + new ArrayShapeItemNode(new IdentifierTypeNode('error'), false, new IdentifierTypeNode('string')), + ]), + ]); + + $err = $registry->validate(['ok' => false, 'error' => 123], $boolUnion, 'Result'); + expect($err)->not->toBeNull(); + expect($err?->getMessage())->toContain("Result['error'] must be of type string"); + + $nullUnion = new UnionTypeNode([ + ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new IdentifierTypeNode('error'), false, new IdentifierTypeNode('string')), + new ArrayShapeItemNode(new IdentifierTypeNode('data'), false, new ConstTypeNode(new ConstExprNullNode())), + ]), + ArrayShapeNode::createSealed([ + new ArrayShapeItemNode(new IdentifierTypeNode('error'), false, new ConstTypeNode(new ConstExprNullNode())), + new ArrayShapeItemNode(new IdentifierTypeNode('data'), false, new IdentifierTypeNode('int')), + ]), + ]); + + $nullErr = $registry->validate(['error' => null, 'data' => 'bad'], $nullUnion, 'Result'); + expect($nullErr)->not->toBeNull(); + expect($nullErr?->getMessage())->toContain("Result['data'] must be of type int"); + }); + }); + + describe('Null Discriminators', function () { + test('reports the matched null-discriminator branch on array shapes', function () { + testNullDiscriminatedArray(['error' => null, 'data' => 42]); + testNullDiscriminatedArray(['error' => 'boom', 'data' => null]); + + expect(fn () => testNullDiscriminatedArray(['error' => null, 'data' => 'bad'])) + ->toThrow(TypeError::class, "Argument \$result['data'] must be of type int") + ; + + expect(fn () => testNullDiscriminatedArray(['error' => 123, 'data' => null])) + ->toThrow(TypeError::class, "Argument \$result['error'] must be of type string") + ; + }); + + test('reports the matched null-discriminator branch on object shapes', function () { + testNullDiscriminatedObject((object) ['error' => null, 'data' => 42]); + testNullDiscriminatedObject((object) ['error' => 'boom', 'data' => null]); + + expect(fn () => testNullDiscriminatedObject((object) ['error' => null, 'data' => 'bad'])) + ->toThrow(TypeError::class, 'Argument $result->data must be of type int') + ; + + expect(fn () => testNullDiscriminatedObject((object) ['error' => 123, 'data' => null])) + ->toThrow(TypeError::class, 'Argument $result->error must be of type string') + ; + }); + }); + + describe('Strict Type, Multi-Field, and Enum Discriminators', function () { + test('distinguishes int 1 from string "1" discriminators strictly', function () { + testIntVsStringDiscriminatedArray(['code' => 1, 'msg' => 'ok']); + testIntVsStringDiscriminatedArray(['code' => '1', 'id' => 99]); + + expect(fn () => testIntVsStringDiscriminatedArray(['code' => '1', 'id' => 'bad'])) + ->toThrow(TypeError::class, "Argument \$payload['id'] must be of type int") + ; + }); + + test('checks all literal discriminator fields when a shape shares a common literal field', function () { + testMultiFieldDiscriminatedArray(['version' => 1, 'ok' => true, 'data' => 10]); + testMultiFieldDiscriminatedArray(['version' => 1, 'ok' => false, 'error' => 'nope']); + + expect(fn () => testMultiFieldDiscriminatedArray(['version' => 1, 'ok' => false, 'error' => 123])) + ->toThrow(TypeError::class, "Argument \$payload['error'] must be of type string") + ; + }); + + test('resolves enum case ConstFetchNode discriminators strictly', function () { + testEnumDiscriminatedArray(['kind' => DiscriminatorTestEvent::Created, 'id' => 1]); + testEnumDiscriminatedArray(['kind' => DiscriminatorTestEvent::Deleted, 'reason' => 'expired']); + + expect(fn () => testEnumDiscriminatedArray(['kind' => DiscriminatorTestEvent::Deleted, 'reason' => 123])) + ->toThrow(TypeError::class, "Argument \$event['reason'] must be of type string") + ; + }); + }); +}); From 7263b5a2ed071032a313b0ba8c4f20451cc28677 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sat, 5 Dec 2026 13:21:59 +0800 Subject: [PATCH 18/24] Enhance ArrayLiteralEvaluator with new integer acceptance checks and add DynamicNumericStringKeyEliminationTest for comprehensive coverage of dynamic numeric string keys in array evaluations. --- .../Evaluator/ArrayLiteralEvaluator.php | 85 ++++++++-- ...DynamicNumericStringKeyEliminationTest.php | 151 ++++++++++++++++++ 2 files changed, 227 insertions(+), 9 deletions(-) create mode 100644 tests/TypeChecking/ArraysAndShapes/DynamicNumericStringKeyEliminationTest.php diff --git a/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php b/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php index 8fb63a10..ff9ecf96 100644 --- a/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php +++ b/src/Internal/Ast/Elimination/Evaluator/ArrayLiteralEvaluator.php @@ -7,7 +7,6 @@ use PhpParser\Node\Expr; use PhpParser\Node\Expr\Array_; use PhpParser\Node\Expr\BinaryOp\Concat; -use PhpParser\Node\Expr\UnaryMinus; use PhpParser\Node\Scalar\Encapsed; use PhpParser\Node\Scalar\EncapsedStringPart; use PhpParser\Node\Scalar\LNumber; @@ -18,7 +17,9 @@ use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode; use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; +use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; +use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; use TypePHP\Internal\Ast\Elimination\StaticTypeEvaluator; /** @@ -52,6 +53,23 @@ final class ArrayLiteralEvaluator 'iterable' => true, ]; + /** + * O(1) hash map of identifier types satisfied by every possible PHP integer. + * + * @var array + */ + private const ANY_INT_ALLOWED_IDENTIFIERS = [ + 'int' => true, + 'integer' => true, + 'array-key' => true, + 'scalar' => true, + 'numeric' => true, + 'number' => true, + 'float' => true, + 'double' => true, + 'mixed' => true, + ]; + /** * Determines whether an AST array expression satisfies a target type contract. * @@ -285,14 +303,8 @@ private static function satisfiesKeyValueArray( return false; } - if ($mayCoerceToInt) { - if ( - ! StaticTypeEvaluator::satisfies(new LNumber(0), $keyType, $currentFile, $trustedVariableTypes, $currentNamespace) - || ! StaticTypeEvaluator::satisfies(new LNumber(1), $keyType, $currentFile, $trustedVariableTypes, $currentNamespace) - || ! StaticTypeEvaluator::satisfies(new UnaryMinus(new LNumber(1)), $keyType, $currentFile, $trustedVariableTypes, $currentNamespace) - ) { - return false; - } + if ($mayCoerceToInt && ! self::acceptsAnyInt($keyType)) { + return false; } if (! StaticTypeEvaluator::satisfies($item->value, $valueType, $currentFile, $trustedVariableTypes, $currentNamespace)) { @@ -502,4 +514,59 @@ private static function hasConcreteItem(Array_ $arrayExpr): bool return false; } + + /** + * Determines whether a key TypeNode deterministically accepts every possible PHP integer + * (PHP_INT_MIN .. PHP_INT_MAX), preventing false static proofs for narrow ranges or literal unions. + */ + private static function acceptsAnyInt(TypeNode $typeNode): bool + { + while ($typeNode instanceof NullableTypeNode) { + $typeNode = $typeNode->type; + } + + if ($typeNode instanceof UnionTypeNode) { + foreach ($typeNode->types as $member) { + if (self::acceptsAnyInt($member)) { + return true; + } + } + + return false; + } + + if ($typeNode instanceof IdentifierTypeNode) { + return isset(self::ANY_INT_ALLOWED_IDENTIFIERS[strtolower($typeNode->name)]); + } + + if ($typeNode instanceof GenericTypeNode) { + $base = strtolower((string) $typeNode->type); + if ($base !== 'int' && $base !== 'integer') { + return false; + } + + return self::isUnboundedRangeBound($typeNode->genericTypes[0] ?? null, 'min') + && self::isUnboundedRangeBound($typeNode->genericTypes[1] ?? null, 'max'); + } + + return false; + } + + /** + * Checks whether a range bound node is omitted or explicitly unbounded ('min'/'max'/'*'). + */ + private static function isUnboundedRangeBound(?TypeNode $boundNode, string $unboundedKeyword): bool + { + if ($boundNode === null) { + return true; + } + + if ($boundNode instanceof IdentifierTypeNode) { + $lower = strtolower($boundNode->name); + + return $lower === $unboundedKeyword || $lower === '*'; + } + + return false; + } } diff --git a/tests/TypeChecking/ArraysAndShapes/DynamicNumericStringKeyEliminationTest.php b/tests/TypeChecking/ArraysAndShapes/DynamicNumericStringKeyEliminationTest.php new file mode 100644 index 00000000..10c7e7a9 --- /dev/null +++ b/tests/TypeChecking/ArraysAndShapes/DynamicNumericStringKeyEliminationTest.php @@ -0,0 +1,151 @@ +, int> + */ +function testDynamicKeyNarrowIntRange(string $suffix): array +{ + return ['1' . $suffix => 42]; +} + +/** + * @return array + */ +function testDynamicKeyLiteralIntUnion(string $suffix): array +{ + return ['1' . $suffix => 42]; +} + +/** + * @return array, int> + */ +function testDynamicKeyUpperBoundedIntRange(string $suffix): array +{ + return ['1' . $suffix => 42]; +} + +/** + * @return array, int> + */ +function testDynamicKeyLowerBoundedIntRange(string $suffix): array +{ + return ['-1' . $suffix => 42]; +} + +/** + * @return array, int> + */ +function testEncapsedDynamicKeyNarrowIntRange(string $suffix): array +{ + return ["1{$suffix}" => 42]; +} + +function parseDynamicKeyTestType(string $typeString): TypeNode +{ + [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); + $tokens = new TokenIterator($lexer->tokenize(DocblockNormalizer::normalize($typeString))); + + return $typeParser->parse($tokens); +} + +describe('Dynamic Numeric String Array Key Elimination Safety', function () { + describe('StaticTypeEvaluator / ArrayLiteralEvaluator', function () { + test('does not prove dynamic numeric string keys satisfy narrow int ranges or literal int unions', function () { + $concatArray = new Array_([ + new ArrayItem( + new LNumber(42), + new Concat(new String_('1'), new Variable('suffix')) + ), + ]); + + $encapsedArray = new Array_([ + new ArrayItem( + new LNumber(42), + new Encapsed([new EncapsedStringPart('1'), new Variable('suffix')]) + ), + ]); + + expect(StaticTypeEvaluator::satisfies($concatArray, parseDynamicKeyTestType('array, int>')))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($concatArray, parseDynamicKeyTestType('array')))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($concatArray, parseDynamicKeyTestType('array, int>')))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($concatArray, parseDynamicKeyTestType('array, int>')))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($concatArray, parseDynamicKeyTestType('non-empty-array, int>')))->toBeFalse(); + expect(StaticTypeEvaluator::satisfies($encapsedArray, parseDynamicKeyTestType('array, int>')))->toBeFalse(); + }); + + test('still proves dynamic keys when key type accepts all ints or string is guaranteed non-numeric', function () { + $numericConcatArray = new Array_([ + new ArrayItem( + new LNumber(42), + new Concat(new String_('1'), new Variable('suffix')) + ), + ]); + + $nonNumericConcatArray = new Array_([ + new ArrayItem( + new LNumber(42), + new Concat(new String_('user_'), new Variable('suffix')) + ), + ]); + + expect(StaticTypeEvaluator::satisfies($numericConcatArray, parseDynamicKeyTestType('array')))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies($numericConcatArray, parseDynamicKeyTestType('array')))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies($numericConcatArray, parseDynamicKeyTestType('array|string, int>')))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies($nonNumericConcatArray, parseDynamicKeyTestType('array')))->toBeTrue(); + expect(StaticTypeEvaluator::satisfies($nonNumericConcatArray, parseDynamicKeyTestType('array, int>')))->toBeTrue(); + }); + }); + + describe('End-to-End Runtime Enforcement', function () { + test('rejects coerced out-of-range integer keys on array, int>', function () { + expect(testDynamicKeyNarrowIntRange('abc'))->toBe(['1abc' => 42]); + expect(testDynamicKeyNarrowIntRange(''))->toBe([1 => 42]); + + expect(fn () => testDynamicKeyNarrowIntRange('00')) + ->toThrow(TypeError::class, 'Return value key must be of type') + ; + + expect(fn () => testEncapsedDynamicKeyNarrowIntRange('00')) + ->toThrow(TypeError::class, 'Return value key must be of type') + ; + }); + + test('rejects coerced integer keys outside literal union array', function () { + expect(testDynamicKeyLiteralIntUnion('x'))->toBe(['1x' => 42]); + expect(testDynamicKeyLiteralIntUnion(''))->toBe([1 => 42]); + + expect(fn () => testDynamicKeyLiteralIntUnion('00')) + ->toThrow(TypeError::class, 'Return value key must be of type') + ; + }); + + test('rejects coerced integer keys outside one-sided int ranges (int and int<-10, max>)', function () { + expect(testDynamicKeyUpperBoundedIntRange(''))->toBe([1 => 42]); + expect(testDynamicKeyLowerBoundedIntRange(''))->toBe([-1 => 42]); + + expect(fn () => testDynamicKeyUpperBoundedIntRange('00')) + ->toThrow(TypeError::class, 'Return value key must be of type') + ; + + expect(fn () => testDynamicKeyLowerBoundedIntRange('00')) + ->toThrow(TypeError::class, 'Return value key must be of type') + ; + }); + }); +}); From 7c33fcf2f4cc6e9d9fa943e6413ff5017cb0392f Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sat, 5 Dec 2026 13:31:24 +0800 Subject: [PATCH 19/24] Add reset method to UnionValidator and update TypeValidatorRegistry to call it during reset --- src/Internal/Util/Config.php | 1 - src/Internal/Validator/TypeValidatorRegistry.php | 1 + src/Internal/Validator/UnionValidator.php | 5 +++++ 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/Internal/Util/Config.php b/src/Internal/Util/Config.php index 14a5b697..8a7df4ec 100644 --- a/src/Internal/Util/Config.php +++ b/src/Internal/Util/Config.php @@ -856,7 +856,6 @@ private static function mergeConfig(array $base, array $overrides): array public static function reset(): void { self::$cachedConfig = null; - ContractVisitor::reset(); self::$projectRoot = null; self::$resolvedConfigFile = null; self::$enabled = true; diff --git a/src/Internal/Validator/TypeValidatorRegistry.php b/src/Internal/Validator/TypeValidatorRegistry.php index 15ed3f6c..6c384fba 100644 --- a/src/Internal/Validator/TypeValidatorRegistry.php +++ b/src/Internal/Validator/TypeValidatorRegistry.php @@ -57,6 +57,7 @@ public static function reset(): void ArrayShapeValidator::reset(); ObjectShapeValidator::reset(); ConstValidator::reset(); + UnionValidator::reset(); } public function __construct() diff --git a/src/Internal/Validator/UnionValidator.php b/src/Internal/Validator/UnionValidator.php index 06395ad1..d699cbdd 100644 --- a/src/Internal/Validator/UnionValidator.php +++ b/src/Internal/Validator/UnionValidator.php @@ -58,6 +58,11 @@ final class UnionValidator implements TypeValidatorInterface */ private static ?WeakMap $compiledUnionCache = null; + public static function reset(): void + { + self::$compiledUnionCache = null; + } + public function validate(mixed $value, TypeNode $node, string $context, TypeValidatorRegistry $registry, bool $isSensitive = false): ?ErrorMessage { /** @var UnionTypeNode $unionNode */ From 3aa555a3323670f69282ffd290d45a3618b8fc8f Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sat, 5 Dec 2026 14:51:21 +0800 Subject: [PATCH 20/24] Refactor RuntimeTypeChecker to replace cloneWith with executeClone and update tests for generic binding preservation and error handling --- src/Internal/RuntimeTypeChecker.php | 62 ------------- tests/Internal/RuntimeTypeCheckerTest.php | 93 ++++++++++++------- .../Boundaries/Php85CloneWithTest.php | 28 +++--- 3 files changed, 75 insertions(+), 108 deletions(-) diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index a8680d7b..0f77f476 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -3048,68 +3048,6 @@ public static function executeCloneWith( return $cloned; } - /** - * Registers a pending clone source object before clone execution. - */ - public static function prepareClone(mixed $original): mixed - { - if (\is_object($original)) { - TemplateManager::pushPendingCloneSource($original); - } - - return $original; - } - - /** - * Copies generic template bindings from an original object to a cloned object instance. - */ - public static function cloneInstance(mixed $cloned, mixed $original = null): mixed - { - $popped = TemplateManager::popPendingCloneSource(); - $source = \is_object($original) ? $original : $popped; - - if (\is_object($cloned) && \is_object($source)) { - TemplateManager::copyInstanceBindings($source, $cloned); - } - - return $cloned; - } - - /** - * PHP 8.5: Copies generic bindings and validates overridden properties on clone($obj, [...]). - * - * @param array|null $overriddenProperties - */ - public static function cloneWith( - mixed $cloned, - mixed $original = null, - ?array $overriddenProperties = null, - string $file = '', - ?int $line = null, - ): mixed { - $popped = TemplateManager::popPendingCloneSource(); - $source = \is_object($original) ? $original : $popped; - - if (! \is_object($cloned) || ! \is_object($source)) { - return $cloned; - } - - TemplateManager::copyInstanceBindings($source, $cloned); - - if ($overriddenProperties !== null && $overriddenProperties !== [] && self::$isEnabled && Config::isInlinePropertiesEnabled()) { - foreach ($overriddenProperties as $propName => $propValue) { - $res = self::checkProperty($propValue, $cloned, (string) $propName, $file); - if ($res instanceof ErrorMessage) { - $typeError = new \TypePHP\Exception\TypeError($res->getMessage()); - - throw ErrorFactory::prepareException($typeError, $line, $file !== '' ? $file : null); - } - } - } - - return $cloned; - } - /** * Evaluates PHP's native increment (++) semantics without mutating the caller's slot. */ diff --git a/tests/Internal/RuntimeTypeCheckerTest.php b/tests/Internal/RuntimeTypeCheckerTest.php index a5b0a2a2..4bc49952 100644 --- a/tests/Internal/RuntimeTypeCheckerTest.php +++ b/tests/Internal/RuntimeTypeCheckerTest.php @@ -367,14 +367,29 @@ function runtimeUnconstrainedReturn(): mixed expect(RuntimeTypeChecker::wrapIterable('nonExistent', 'arg', $iter))->toBe($iter); }); - test('prepareClone and cloneInstance clone generic bindings', function () { - $dog = new Dog(); - expect(RuntimeTypeChecker::prepareClone($dog))->toBe($dog); - expect(RuntimeTypeChecker::prepareClone(123))->toBe(123); + test('executeClone propagates generic bindings and restores pending clone source on exception', function () { + $original = new Container(new Dog()); + TemplateManager::bindInstance($original, Container::class . '<' . Dog::class . '>'); + + $cloned = RuntimeTypeChecker::executeClone($original, static fn (mixed $src): mixed => clone $src); + + expect($cloned)->toBeInstanceOf(Container::class) + ->and($cloned)->not()->toBe($original) + ->and(TypePHP\TypePHP::getGenericType($cloned))->toBe(Dog::class) + ->and(TemplateManager::$pendingCloneSource)->toBeNull() + ; + + expect(RuntimeTypeChecker::executeClone(123, static fn (mixed $src): mixed => $src))->toBe(123); + + expect(function () use ($original) { + RuntimeTypeChecker::executeClone($original, static function () use ($original): never { + expect(TemplateManager::$pendingCloneSource)->toBe($original); - $cloned = new Dog(); - expect(RuntimeTypeChecker::cloneInstance($cloned, $dog))->toBe($cloned); - expect(RuntimeTypeChecker::cloneInstance(123, 456))->toBe(123); + throw new RuntimeException('clone failed'); + }); + })->toThrow(RuntimeException::class, 'clone failed'); + + expect(TemplateManager::$pendingCloneSource)->toBeNull(); }); test('inferTypeFromValue and getRegistry helpers', function () { @@ -566,49 +581,61 @@ function vendorAction(): void expect(RuntimeTypeChecker::checkReturn('runtimeUnconstrainedReturn', 100))->toBe(100); }); - test('returns cloned value untouched when cloned or source is not an object', function () { - expect(RuntimeTypeChecker::cloneWith(123, new stdClass()))->toBe(123); - expect(RuntimeTypeChecker::cloneWith('string', null))->toBe('string'); - expect(RuntimeTypeChecker::cloneWith(null, null))->toBeNull(); + test('executeCloneWith returns value untouched when original or cloned result is not an object', function () { + expect(RuntimeTypeChecker::executeCloneWith(123, [], static fn (mixed $src): mixed => $src))->toBe(123); + expect(RuntimeTypeChecker::executeCloneWith('string', null, static fn (mixed $src): mixed => $src))->toBe('string'); + expect(RuntimeTypeChecker::executeCloneWith(null, null, static fn (mixed $src): mixed => $src))->toBeNull(); - TemplateManager::$pendingCloneSource = null; $obj = new stdClass(); - expect(RuntimeTypeChecker::cloneWith($obj, null))->toBe($obj); - expect(RuntimeTypeChecker::cloneWith($obj, 456))->toBe($obj); + expect(RuntimeTypeChecker::executeCloneWith($obj, ['score' => -1], static fn (): int => 456))->toBe(456); + expect(TemplateManager::$pendingCloneSource)->toBeNull(); }); - test('copies generic bindings using explicit original object argument', function () { + test('executeCloneWith copies generic bindings to cloned object', function () { $original = new Container(new Dog()); TemplateManager::bindInstance($original, Container::class . '<' . Dog::class . '>'); $cloned = new Container(new Dog()); - $result = RuntimeTypeChecker::cloneWith($cloned, $original); + $result = RuntimeTypeChecker::executeCloneWith($original, [], static fn (): object => $cloned); expect($result)->toBe($cloned) ->and(TypePHP\TypePHP::getGenericType($cloned))->toBe(Dog::class) + ->and(TemplateManager::$pendingCloneSource)->toBeNull() ; }); - test('falls back to TemplateManager::$pendingCloneSource and resets it to null', function () { + test('executeCloneWith pushes pending clone source during cloner callback and resets it to null on exit or exception', function () { $original = new Container(new Dog()); TemplateManager::bindInstance($original, Container::class . '<' . Dog::class . '>'); - TemplateManager::$pendingCloneSource = $original; - + $seenDuringClone = null; $cloned = new Container(new Dog()); - $result = RuntimeTypeChecker::cloneWith($cloned, original: null); + $result = RuntimeTypeChecker::executeCloneWith($original, [], static function () use (&$seenDuringClone, $cloned): object { + $seenDuringClone = TemplateManager::$pendingCloneSource; - expect($result)->toBe($cloned) + return $cloned; + }); + + expect($seenDuringClone)->toBe($original) + ->and($result)->toBe($cloned) ->and(TypePHP\TypePHP::getGenericType($cloned))->toBe(Dog::class) ->and(TemplateManager::$pendingCloneSource)->toBeNull() ; + + expect(function () use ($original) { + RuntimeTypeChecker::executeCloneWith($original, [], static function (): never { + throw new RuntimeException('clone-with failed'); + }); + })->toThrow(RuntimeException::class, 'clone-with failed'); + + expect(TemplateManager::$pendingCloneSource)->toBeNull(); }); - test('skips property validation when overriddenProperties is null or empty array', function () { + test('executeCloneWith skips property validation when overriddenProperties is null or empty array', function () { $obj = new stdClass(); - expect(RuntimeTypeChecker::cloneWith($obj, $obj, null))->toBe($obj) - ->and(RuntimeTypeChecker::cloneWith($obj, $obj, []))->toBe($obj) + expect(RuntimeTypeChecker::executeCloneWith($obj, null, static fn (mixed $src): mixed => $src))->toBe($obj) + ->and(RuntimeTypeChecker::executeCloneWith($obj, [], static fn (mixed $src): mixed => $src))->toBe($obj) ; }); @@ -622,10 +649,10 @@ function vendorAction(): void $model = new TypePHP\Tests\Fixtures\Php85\CloneWithModelFixture(); $cloned = clone $model; - $result = RuntimeTypeChecker::cloneWith( - $cloned, + $result = RuntimeTypeChecker::executeCloneWith( $model, ['score' => 50, 'name' => 'Bob'], + static fn (): object => $cloned, __FILE__, 100 ); @@ -644,10 +671,10 @@ function vendorAction(): void $cloned = clone $model; expect(function () use ($cloned, $model) { - RuntimeTypeChecker::cloneWith( - $cloned, + RuntimeTypeChecker::executeCloneWith( $model, ['score' => -25], + static fn (): object => $cloned, __FILE__, 42 ); @@ -670,10 +697,10 @@ function vendorAction(): void $cloned = clone $model; expect(function () use ($cloned, $model) { - RuntimeTypeChecker::cloneWith( - $cloned, + RuntimeTypeChecker::executeCloneWith( $model, ['name' => ''], + static fn (): object => $cloned, __FILE__, 50 ); @@ -691,10 +718,10 @@ function vendorAction(): void $cloned = clone $order; expect(function () use ($cloned, $order) { - RuntimeTypeChecker::cloneWith( - $cloned, + RuntimeTypeChecker::executeCloneWith( $order, ['id' => -999], + static fn (): object => $cloned, __FILE__, 60 ); @@ -713,7 +740,7 @@ function vendorAction(): void $model = new TypePHP\Tests\Fixtures\Php85\CloneWithModelFixture(); $cloned = clone $model; - $result = RuntimeTypeChecker::cloneWith($cloned, $model, ['score' => -50]); + $result = RuntimeTypeChecker::executeCloneWith($model, ['score' => -50], static fn (): object => $cloned); expect($result)->toBe($cloned); }); diff --git a/tests/TypeChecking/Boundaries/Php85CloneWithTest.php b/tests/TypeChecking/Boundaries/Php85CloneWithTest.php index c46db42a..bb03d011 100644 --- a/tests/TypeChecking/Boundaries/Php85CloneWithTest.php +++ b/tests/TypeChecking/Boundaries/Php85CloneWithTest.php @@ -48,14 +48,16 @@ }); describe('2. Runtime Generic Type Preservation via WeakMap', function () { - test('preserves generic template bindings when cloning an object with cloneWith helper', function () { + test('preserves generic template bindings when cloning an object with executeCloneWith helper', function () { /** @var GenericBox $original */ $original = new GenericBox(); $original->set(new Dog()); - $cloned = clone $original; - - RuntimeTypeChecker::cloneWith($cloned, $original); + $cloned = RuntimeTypeChecker::executeCloneWith( + $original, + [], + static fn (): object => new GenericBox() + ); expect(TypePHP::getGenericType($cloned))->toBe(Dog::class); @@ -73,10 +75,10 @@ $user = new CloneWithModelFixture(); $cloned = clone $user; - $result = RuntimeTypeChecker::cloneWith( - $cloned, + $result = RuntimeTypeChecker::executeCloneWith( $user, ['score' => 50, 'name' => 'Bob'], + static fn (): object => $cloned, __FILE__, __LINE__ ); @@ -89,10 +91,10 @@ $cloned = clone $user; expect(function () use ($cloned, $user) { - RuntimeTypeChecker::cloneWith( - $cloned, + RuntimeTypeChecker::executeCloneWith( $user, ['score' => -5], + static fn (): object => $cloned, __FILE__, __LINE__ ); @@ -104,25 +106,25 @@ $cloned = clone $user; expect(function () use ($cloned, $user) { - RuntimeTypeChecker::cloneWith( - $cloned, + RuntimeTypeChecker::executeCloneWith( $user, ['name' => ''], + static fn (): object => $cloned, __FILE__, __LINE__ ); })->toThrow(TypeError::class, 'non-empty-string'); }); - test('validates overridden properties on readonly classes during cloneWith', function () { + test('validates overridden properties on readonly classes during executeCloneWith', function () { $order = new CloneWithReadonlyOrder(100, 'SKU-ORIGINAL'); $cloned = clone $order; expect(function () use ($cloned, $order) { - RuntimeTypeChecker::cloneWith( - $cloned, + RuntimeTypeChecker::executeCloneWith( $order, ['id' => -999], + static fn (): object => $cloned, __FILE__, __LINE__ ); From 460c9e729eca98001253ebac1bc0d245af80bd3d Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sat, 5 Dec 2026 15:23:01 +0800 Subject: [PATCH 21/24] Refactor TemplateManager to unify union and intersection checks with variance handling; add InvariantNullableUnionVarianceTest for comprehensive coverage of variance behavior in generics. --- src/Internal/Generics/TemplateManager.php | 26 +- .../InvariantNullableUnionVarianceTest.php | 264 ++++++++++++++++++ 2 files changed, 277 insertions(+), 13 deletions(-) create mode 100644 tests/TypeChecking/Generics/InvariantNullableUnionVarianceTest.php diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 96431264..af872c7f 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -3594,7 +3594,7 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str } if ($expected instanceof UnionTypeNode && $variance !== GenericTypeNode::VARIANCE_INVARIANT) { - return self::checkExpectedUnionCovariant($existing, $expected); + return self::checkExpectedUnion($existing, $expected, $variance); } if ($existing instanceof UnionTypeNode && $variance !== GenericTypeNode::VARIANCE_INVARIANT) { @@ -3602,11 +3602,11 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str } if ($expected instanceof IntersectionTypeNode && $variance !== GenericTypeNode::VARIANCE_INVARIANT) { - return self::checkExpectedIntersectionCovariant($existing, $expected); + return self::checkExpectedIntersection($existing, $expected, $variance); } if ($existing instanceof IntersectionTypeNode && $variance !== GenericTypeNode::VARIANCE_INVARIANT) { - return self::checkExistingIntersectionCovariant($existing, $expected); + return self::checkExistingIntersection($existing, $expected, $variance); } if ($existing instanceof ArrayTypeNode && $expected instanceof ArrayTypeNode) { @@ -3725,7 +3725,7 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str } if ($expected instanceof UnionTypeNode) { - return self::checkExpectedUnionCovariant($existing, $expected); + return self::checkExpectedUnion($existing, $expected, $variance); } if ($existing instanceof UnionTypeNode) { @@ -3733,11 +3733,11 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str } if ($expected instanceof IntersectionTypeNode) { - return self::checkExpectedIntersectionCovariant($existing, $expected); + return self::checkExpectedIntersection($existing, $expected, $variance); } if ($existing instanceof IntersectionTypeNode) { - return self::checkExistingIntersectionCovariant($existing, $expected); + return self::checkExistingIntersection($existing, $expected, $variance); } $existingStr = (string) $existing; @@ -3879,7 +3879,7 @@ private static function isScalarSubtype(string $sub, string $super): bool return false; } - private static function checkExpectedUnionCovariant(TypeNode $existing, UnionTypeNode $expected): bool + private static function checkExpectedUnion(TypeNode $existing, UnionTypeNode $expected, string $variance): bool { if ($existing instanceof IdentifierTypeNode) { self::$compiledUnionMembersCache ??= new WeakMap(); @@ -3914,7 +3914,7 @@ private static function checkExpectedUnionCovariant(TypeNode $existing, UnionTyp if ($existing instanceof UnionTypeNode) { foreach ($existing->types as $existingVariant) { - if (! self::checkExpectedUnionCovariant($existingVariant, $expected)) { + if (! self::checkExpectedUnion($existingVariant, $expected, $variance)) { return false; } } @@ -3923,7 +3923,7 @@ private static function checkExpectedUnionCovariant(TypeNode $existing, UnionTyp } foreach ($expected->types as $unionVariant) { - if (self::checkVariance($existing, $unionVariant, GenericTypeNode::VARIANCE_COVARIANT)) { + if (self::checkVariance($existing, $unionVariant, $variance)) { return true; } } @@ -3942,10 +3942,10 @@ private static function checkExistingUnionCovariant(UnionTypeNode $existing, Typ return true; } - private static function checkExpectedIntersectionCovariant(TypeNode $existing, IntersectionTypeNode $expected): bool + private static function checkExpectedIntersection(TypeNode $existing, IntersectionTypeNode $expected, string $variance): bool { foreach ($expected->types as $intersectionMember) { - if (! self::checkVariance($existing, $intersectionMember, GenericTypeNode::VARIANCE_COVARIANT)) { + if (! self::checkVariance($existing, $intersectionMember, $variance)) { return false; } } @@ -3953,10 +3953,10 @@ private static function checkExpectedIntersectionCovariant(TypeNode $existing, I return true; } - private static function checkExistingIntersectionCovariant(IntersectionTypeNode $existing, TypeNode $expected): bool + private static function checkExistingIntersection(IntersectionTypeNode $existing, TypeNode $expected, string $variance): bool { foreach ($existing->types as $existingMember) { - if (self::checkVariance($existingMember, $expected, GenericTypeNode::VARIANCE_COVARIANT)) { + if (self::checkVariance($existingMember, $expected, $variance)) { return true; } } diff --git a/tests/TypeChecking/Generics/InvariantNullableUnionVarianceTest.php b/tests/TypeChecking/Generics/InvariantNullableUnionVarianceTest.php new file mode 100644 index 00000000..d1dab054 --- /dev/null +++ b/tests/TypeChecking/Generics/InvariantNullableUnionVarianceTest.php @@ -0,0 +1,264 @@ + + */ + public array $items = []; + + /** + * @param T $item + */ + public function add(mixed $item): void + { + $this->items[] = $item; + } +} + +/** + * @template-covariant T + */ +final class CovariantVarianceBox +{ + /** + * @param T|null $item + */ + public function __construct(public mixed $item = null) + { + } +} + +/** + * @template-contravariant T + */ +final class ContravariantVarianceBox +{ + /** + * @param callable(T): void $handler + */ + public function __construct(public mixed $handler) + { + } +} + +/** + * @param InvariantVarianceBox $box + */ +function testAcceptNullableAnimalBox(InvariantVarianceBox $box): void +{ +} + +/** + * @param InvariantVarianceBox $box + */ +function testAcceptUnionNullAnimalBox(InvariantVarianceBox $box): void +{ +} + +/** + * @param InvariantVarianceBox $box + */ +function testAcceptUnionAnimalOrCarBox(InvariantVarianceBox $box): void +{ +} + +/** + * @param InvariantVarianceBox $box + */ +function testAcceptIntersectionAnimalCountableBox(InvariantVarianceBox $box): void +{ +} + +/** + * @param InvariantVarianceBox $box + */ +function testAcceptInvariantAnimalBox(InvariantVarianceBox $box): void +{ +} + +/** + * @param InvariantVarianceBox $box + */ +function testAcceptNullableDogBox(InvariantVarianceBox $box): void +{ +} + +/** + * @param InvariantVarianceBox $box + */ +function testAcceptDogOrCatBox(InvariantVarianceBox $box): void +{ +} + +/** + * @param InvariantVarianceBox $box + */ +function testAcceptDogCatOrCarBox(InvariantVarianceBox $box): void +{ +} + +/** + * @param InvariantVarianceBox $box + */ +function testAcceptNullableIntBox(InvariantVarianceBox $box): void +{ +} + +/** + * @param InvariantVarianceBox $box + */ +function testAcceptNullableArrayKeyBox(InvariantVarianceBox $box): void +{ +} + +/** + * @param InvariantVarianceBox $box + */ +function testAcceptBroadUpperBoundUnionBox(InvariantVarianceBox $box): void +{ +} + +/** + * @param InvariantVarianceBox $box + */ +function testAcceptCountableArrayAccessBox(InvariantVarianceBox $box): void +{ +} + +/** + * @param InvariantVarianceBox $box + */ +function testAcceptUseSiteCovariantNullableAnimalBox(InvariantVarianceBox $box): void +{ +} + +/** + * @param CovariantVarianceBox $box + */ +function testAcceptCovariantProducerNullableAnimalBox(CovariantVarianceBox $box): void +{ +} + +/** + * @param ContravariantVarianceBox $box + */ +function testAcceptContravariantDogBox(ContravariantVarianceBox $box): void +{ +} + +describe('Invariant Class Hierarchy Enforcement Inside Nullable, Union, and Intersection Generics', function () { + describe('Rejects Class-Hierarchy Covariance Leaks Under Invariance', function () { + test('rejects Box when Box, Box, or Box is expected', function () { + /** @var InvariantVarianceBox $dogBox */ + $dogBox = new InvariantVarianceBox(); + + expect(fn () => testAcceptNullableAnimalBox($dogBox)) + ->toThrow(TypeError::class, 'expects ' . InvariantVarianceBox::class) + ; + + expect(fn () => testAcceptUnionNullAnimalBox($dogBox)) + ->toThrow(TypeError::class, 'expects ' . InvariantVarianceBox::class) + ; + + expect(fn () => testAcceptUnionAnimalOrCarBox($dogBox)) + ->toThrow(TypeError::class, 'expects ' . InvariantVarianceBox::class) + ; + }); + + test('rejects Box when Box is expected', function () { + /** @var InvariantVarianceBox $dogOrCarBox */ + $dogOrCarBox = new InvariantVarianceBox(); + + expect(fn () => testAcceptUnionAnimalOrCarBox($dogOrCarBox)) + ->toThrow(TypeError::class, 'expects ' . InvariantVarianceBox::class) + ; + }); + + test('rejects Box when Box or Box is expected', function () { + /** @var InvariantVarianceBox $dogCountableBox */ + $dogCountableBox = new InvariantVarianceBox(); + + expect(fn () => testAcceptIntersectionAnimalCountableBox($dogCountableBox)) + ->toThrow(TypeError::class, 'expects ' . InvariantVarianceBox::class) + ; + + expect(fn () => testAcceptInvariantAnimalBox($dogCountableBox)) + ->toThrow(TypeError::class, 'expects ' . InvariantVarianceBox::class) + ; + }); + + test('rejects inline @var reassignment of Box into Box', function () { + /** @var InvariantVarianceBox $dogBox */ + $dogBox = new InvariantVarianceBox(); + + expect(function () use ($dogBox) { + /** @var InvariantVarianceBox $animalBox */ + $animalBox = $dogBox; + + return $animalBox; + })->toThrow(TypeError::class, 'expects ' . InvariantVarianceBox::class); + }); + }); + + describe('Preserves Pragmatic Subset Widening & Explicit Covariance/Contravariance', function () { + test('still permits exact union subsets, scalar refinements, upper-bound object, and intersection widening while keeping WeakMap write protection', function () { + /** @var InvariantVarianceBox $dogBox */ + $dogBox = new InvariantVarianceBox(); + $dogBox->add(new Dog()); + + testAcceptNullableDogBox($dogBox); + testAcceptDogOrCatBox($dogBox); + testAcceptBroadUpperBoundUnionBox($dogBox); + + // WeakMap remains pinned to Dog + expect(TypePHP::getGenericType($dogBox))->toBe(Dog::class); + expect(fn () => $dogBox->add(null)) + ->toThrow(TypeError::class, Dog::class) + ; + + /** @var InvariantVarianceBox $petBox */ + $petBox = new InvariantVarianceBox(); + testAcceptDogCatOrCarBox($petBox); + + /** @var InvariantVarianceBox $posIntBox */ + $posIntBox = new InvariantVarianceBox(); + testAcceptNullableIntBox($posIntBox); + + /** @var InvariantVarianceBox $strBox */ + $strBox = new InvariantVarianceBox(); + testAcceptNullableArrayKeyBox($strBox); + + /** @var InvariantVarianceBox $wideIntersectionBox */ + $wideIntersectionBox = new InvariantVarianceBox(); + testAcceptCountableArrayAccessBox($wideIntersectionBox); + }); + + test('still permits class covariance under @template-covariant, use-site , and @template-contravariant', function () { + /** @var InvariantVarianceBox $dogBox */ + $dogBox = new InvariantVarianceBox(); + testAcceptUseSiteCovariantNullableAnimalBox($dogBox); + + /** @var CovariantVarianceBox $covDogBox */ + $covDogBox = new CovariantVarianceBox(new Dog()); + testAcceptCovariantProducerNullableAnimalBox($covDogBox); + + /** @var ContravariantVarianceBox $contraAnimalBox */ + $contraAnimalBox = new ContravariantVarianceBox(static fn (?Animal $a): mixed => null); + testAcceptContravariantDogBox($contraAnimalBox); + + expect(true)->toBeTrue(); + }); + }); +}); From 78a3f8ea2de459e490b544ff69a91fb8cad10eec Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sat, 5 Dec 2026 16:19:27 +0800 Subject: [PATCH 22/24] Enhance IterableWrapper and add tests for union and nullable iterable handling; introduce UnionIterableMapFixture for improved type checking in union scenarios. --- src/Internal/Wrapper/IterableWrapper.php | 87 +++++++++++++++++-- .../NullableAndUnionIterableReturnTest.php | 70 +++++++++++++++ 2 files changed, 149 insertions(+), 8 deletions(-) diff --git a/src/Internal/Wrapper/IterableWrapper.php b/src/Internal/Wrapper/IterableWrapper.php index 125e5c85..290d1a96 100644 --- a/src/Internal/Wrapper/IterableWrapper.php +++ b/src/Internal/Wrapper/IterableWrapper.php @@ -9,7 +9,9 @@ use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode; use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; +use PHPStan\PhpDocParser\Ast\Type\IntersectionTypeNode; use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode; +use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode; use Traversable; @@ -258,10 +260,35 @@ private static function resolveKeyAndItemTypes( } } + while ($typeNode instanceof NullableTypeNode) { + $typeNode = $typeNode->type; + } + + if ($typeNode instanceof UnionTypeNode) { + $nonNullNode = null; + $nonNullCount = 0; + foreach ($typeNode->types as $member) { + if ($member instanceof IdentifierTypeNode && strtolower($member->name) === 'null') { + continue; + } + $nonNullCount++; + $nonNullNode = $member; + } + if ($nonNullCount === 1 && $nonNullNode !== null) { + $typeNode = $nonNullNode; + } + } + + $baseName = ''; + if ($typeNode instanceof IdentifierTypeNode) { + $baseName = strtolower(ltrim($typeNode->name, '\\')); + } elseif ($typeNode instanceof GenericTypeNode) { + $baseName = strtolower(ltrim((string) $typeNode->type, '\\')); + } + $result = null; - $traversableNode = self::extractTraversableTypeNode($typeNode, null, $plan['aliases']); - if ($traversableNode !== null) { - [$keyTypeNode, $itemTypeNode] = self::extractKeyAndItemTypeNodes($traversableNode, $plan['aliases']); + if (isset(self::STANDARD_ITERABLES[$baseName])) { + [$keyTypeNode, $itemTypeNode] = self::extractKeyAndItemTypeNodes($typeNode, $plan['aliases']); if (! self::isUnconstrainedKey($keyTypeNode) || ! self::isUnconstrained($itemTypeNode)) { $result = [$keyTypeNode, $itemTypeNode]; } @@ -473,7 +500,12 @@ private static function extractTraversableTypeNode(TypeNode $typeNode, mixed $it { /** @var list $matches */ $matches = []; - self::collectTraversableBranches($typeNode, $iterable, $aliases, $matches); + $hasOtherMatchingBranch = false; + self::collectTraversableBranches($typeNode, $iterable, $aliases, $matches, $hasOtherMatchingBranch); + + if ($hasOtherMatchingBranch) { + return null; + } if (\count($matches) === 1) { return $matches[0]; @@ -505,7 +537,8 @@ private static function collectTraversableBranches( TypeNode $typeNode, mixed $iterable, array $aliases, - array &$matches + array &$matches, + bool &$hasOtherMatchingBranch ): void { while ($typeNode instanceof NullableTypeNode) { $typeNode = $typeNode->type; @@ -520,7 +553,7 @@ private static function collectTraversableBranches( if ($typeNode instanceof UnionTypeNode) { foreach ($typeNode->types as $member) { - self::collectTraversableBranches($member, $iterable, $aliases, $matches); + self::collectTraversableBranches($member, $iterable, $aliases, $matches, $hasOtherMatchingBranch); } return; @@ -533,9 +566,47 @@ private static function collectTraversableBranches( $baseName = strtolower(ltrim((string) $typeNode->type, '\\')); } - if ($baseName !== '' && isset(self::STANDARD_ITERABLES[$baseName]) && self::traversableBranchMatchesValue($baseName, $iterable)) { - $matches[] = $typeNode; + if ($baseName !== '' && isset(self::STANDARD_ITERABLES[$baseName])) { + if (self::traversableBranchMatchesValue($baseName, $iterable)) { + $matches[] = $typeNode; + } + + return; + } + + if ($iterable instanceof Traversable && self::nonStandardBranchMatchesTraversable($typeNode, $iterable)) { + $hasOtherMatchingBranch = true; + } + } + + /** + * @param Traversable $iterable + */ + private static function nonStandardBranchMatchesTraversable(TypeNode $typeNode, Traversable $iterable): bool + { + if ($typeNode instanceof IdentifierTypeNode) { + $name = ltrim($typeNode->name, '\\'); + $lower = strtolower($name); + + if ($lower === 'object' || $lower === 'mixed') { + return true; + } + + return ! SpecialTypeResolver::isBuiltInTypeKeyword($name) && ($iterable instanceof $name); } + + if ($typeNode instanceof GenericTypeNode) { + $name = ltrim((string) $typeNode->type, '\\'); + $lower = strtolower($name); + + if ($lower === 'object' || $lower === 'mixed') { + return true; + } + + return ! SpecialTypeResolver::isBuiltInTypeKeyword($name) && ($iterable instanceof $name); + } + + return $typeNode instanceof ObjectShapeNode || $typeNode instanceof IntersectionTypeNode; } private static function traversableBranchMatchesValue(string $baseName, mixed $iterable): bool diff --git a/tests/TypeChecking/CallablesAndIterators/NullableAndUnionIterableReturnTest.php b/tests/TypeChecking/CallablesAndIterators/NullableAndUnionIterableReturnTest.php index e01d08fe..debc72e1 100644 --- a/tests/TypeChecking/CallablesAndIterators/NullableAndUnionIterableReturnTest.php +++ b/tests/TypeChecking/CallablesAndIterators/NullableAndUnionIterableReturnTest.php @@ -2,6 +2,59 @@ declare(strict_types=1); +/** + * @template K + * @template V + * + * @implements IteratorAggregate + */ +final class UnionIterableMapFixture implements IteratorAggregate +{ + /** + * @param array $entries + */ + public function __construct(private array $entries) + { + } + + /** + * @return Traversable + */ + public function getIterator(): Traversable + { + return new ArrayIterator($this->entries); + } +} + +/** + * @template E + * + * @param iterable|Closure():iterable $source + */ +function testUnionIterableOrClosureParamPreservesAggregate(iterable|Closure $source): bool +{ + return $source instanceof IteratorAggregate; +} + +/** + * @template K + * @template V + * + * @param iterable|UnionIterableMapFixture|Closure():iterable $data + */ +function testUnionPairsOrMapParamPreservesMap(iterable|Closure $data): bool +{ + return $data instanceof UnionIterableMapFixture; +} + +/** + * @return iterable|UnionIterableMapFixture + */ +function testReturnUnionPairsOrMap(mixed $val): iterable +{ + return $val; +} + /** * @return ?iterable */ @@ -239,6 +292,23 @@ public function __call(string $name, array $args): mixed ->toThrow(TypeError::class, 'Return iterator value must be of type int') ; }); + + test('does not wrap IteratorAggregate or matching Traversable class branches in union parameters or returns', function () { + /** @var UnionIterableMapFixture $map */ + $map = new UnionIterableMapFixture(['k' => 'value_0']); + + expect(testUnionIterableOrClosureParamPreservesAggregate($map))->toBeTrue(); + expect(testUnionPairsOrMapParamPreservesMap($map))->toBeTrue(); + + $returnedMap = testReturnUnionPairsOrMap($map); + expect($returnedMap)->toBe($map); + expect(iterator_to_array($returnedMap))->toBe(['k' => 'value_0']); + + $badPairs = testReturnUnionPairsOrMap(new ArrayIterator([['k', 'not-an-int']])); + expect(fn () => iterator_to_array($badPairs)) + ->toThrow(TypeError::class, "Return iterator value['1'] must be of type int") + ; + }); }); describe('Generic, Conditional, Alias, and Magic @method Iterable Returns', function () { From 7ed26156b3c09b0b032c6b4de692bcda1728ba32 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sat, 5 Dec 2026 20:58:22 +0800 Subject: [PATCH 23/24] Refactor TemplateManager to improve intersection type handling; add methods for invariant intersection equality and flattening intersection members. Enhance InvariantNullableUnionVarianceTest with new tests for covariant and contravariant variance boxes. --- src/Internal/Generics/TemplateManager.php | 67 ++++++++++++++++- ...omplexUnionAndIntersectionSubtypesTest.php | 59 +++++++++++++-- .../InvariantNullableUnionVarianceTest.php | 72 ++++++++++++++++++- 3 files changed, 186 insertions(+), 12 deletions(-) diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index af872c7f..64cf1c51 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -3732,12 +3732,16 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str return false; } - if ($expected instanceof IntersectionTypeNode) { - return self::checkExpectedIntersection($existing, $expected, $variance); + if ($existing instanceof IntersectionTypeNode && $expected instanceof IntersectionTypeNode) { + return self::checkInvariantIntersectionEquality($existing, $expected); } if ($existing instanceof IntersectionTypeNode) { - return self::checkExistingIntersection($existing, $expected, $variance); + return $expected instanceof IdentifierTypeNode && strtolower($expected->name) === 'object'; + } + + if ($expected instanceof IntersectionTypeNode) { + return false; } $existingStr = (string) $existing; @@ -3964,6 +3968,63 @@ private static function checkExistingIntersection(IntersectionTypeNode $existing return false; } + private static function checkInvariantIntersectionEquality(IntersectionTypeNode $existing, IntersectionTypeNode $expected): bool + { + $existingMembers = self::flattenIntersectionMembers($existing); + $expectedMembers = self::flattenIntersectionMembers($expected); + + foreach ($expectedMembers as $expectedMember) { + $matched = false; + foreach ($existingMembers as $existingMember) { + if (self::checkVariance($existingMember, $expectedMember, GenericTypeNode::VARIANCE_INVARIANT)) { + $matched = true; + + break; + } + } + + if (! $matched) { + return false; + } + } + + foreach ($existingMembers as $existingMember) { + $matched = false; + foreach ($expectedMembers as $expectedMember) { + if (self::checkVariance($existingMember, $expectedMember, GenericTypeNode::VARIANCE_INVARIANT)) { + $matched = true; + + break; + } + } + + if (! $matched) { + return false; + } + } + + return true; + } + + /** + * @return list + */ + private static function flattenIntersectionMembers(IntersectionTypeNode $node): array + { + $members = []; + foreach ($node->types as $member) { + if ($member instanceof IntersectionTypeNode) { + foreach (self::flattenIntersectionMembers($member) as $nested) { + $members[] = $nested; + } + } else { + $members[] = $member; + } + } + + return $members; + } + private static function checkNestedGenericVariance(GenericTypeNode $existing, GenericTypeNode $expected): bool { $expectedClassName = (string) $expected->type; diff --git a/tests/TypeChecking/Generics/ComplexUnionAndIntersectionSubtypesTest.php b/tests/TypeChecking/Generics/ComplexUnionAndIntersectionSubtypesTest.php index 16270be7..5806e572 100644 --- a/tests/TypeChecking/Generics/ComplexUnionAndIntersectionSubtypesTest.php +++ b/tests/TypeChecking/Generics/ComplexUnionAndIntersectionSubtypesTest.php @@ -114,6 +114,17 @@ class TypeSetHolder public array $items = []; } +/** + * @template-covariant T + */ +class CovariantTypeSetHolder +{ + /** + * @var array + */ + public array $items = []; +} + describe('Complex Union, Intersection, and DNF Subtyping Guarantees', function () { describe('Union Subset Assignability', function () { test('allows assigning subset class union into superset class union (Dog|Cat into Dog|Cat|Bird)', function () { @@ -171,15 +182,33 @@ class TypeSetHolder expect($expected)->toBeInstanceOf(TripleInterfaceObject::class); }); - test('allows generic container of triple-interface objects into container expecting double-interface intersection', function () { + test('allows covariant generic container of triple-interface objects into container expecting double-interface intersection', function () { + /** @var CovariantTypeSetHolder $container */ + $container = new CovariantTypeSetHolder(); + + /** @var CovariantTypeSetHolder $tripleContainer */ + $tripleContainer = new CovariantTypeSetHolder(); + + $container = $tripleContainer; + expect($container)->toBe($tripleContainer); + }); + + test('rejects invariant generic container of triple-interface objects into double-interface intersection while allowing reordered exact match', function () { /** @var TypeSetHolder $container */ $container = new TypeSetHolder(); + /** @var TypeSetHolder $reorderedContainer */ + $reorderedContainer = new TypeSetHolder(); + + $container = $reorderedContainer; + expect($container)->toBe($reorderedContainer); + /** @var TypeSetHolder $tripleContainer */ $tripleContainer = new TypeSetHolder(); - $container = $tripleContainer; - expect($container)->toBe($tripleContainer); + expect(function () use (&$container, $tripleContainer) { + $container = $tripleContainer; + })->toThrow(TypeError::class); }); test('strictly rejects object missing one required interface of the intersection', function () { @@ -198,15 +227,33 @@ class TypeSetHolder expect($dnfTarget)->toBeInstanceOf(TripleInterfaceObject::class); }); - test('allows generic container of triple-interface objects into container expecting DNF union', function () { + test('allows covariant generic container of triple-interface objects into container expecting DNF union', function () { + /** @var CovariantTypeSetHolder<(Countable&ArrayAccess)|(Iterator&Countable)> $dnfContainer */ + $dnfContainer = new CovariantTypeSetHolder(); + + /** @var CovariantTypeSetHolder $tripleContainer */ + $tripleContainer = new CovariantTypeSetHolder(); + + $dnfContainer = $tripleContainer; + expect($dnfContainer)->toBe($tripleContainer); + }); + + test('allows exact intersection branch into invariant DNF union while rejecting strict intersection subtype', function () { /** @var TypeSetHolder<(Countable&ArrayAccess)|(Iterator&Countable)> $dnfContainer */ $dnfContainer = new TypeSetHolder(); + /** @var TypeSetHolder $exactBranchContainer */ + $exactBranchContainer = new TypeSetHolder(); + + $dnfContainer = $exactBranchContainer; + expect($dnfContainer)->toBe($exactBranchContainer); + /** @var TypeSetHolder $tripleContainer */ $tripleContainer = new TypeSetHolder(); - $dnfContainer = $tripleContainer; - expect($dnfContainer)->toBe($tripleContainer); + expect(function () use (&$dnfContainer, $tripleContainer) { + $dnfContainer = $tripleContainer; + })->toThrow(TypeError::class); }); test('strictly rejects object failing all branches of the DNF union', function () { diff --git a/tests/TypeChecking/Generics/InvariantNullableUnionVarianceTest.php b/tests/TypeChecking/Generics/InvariantNullableUnionVarianceTest.php index d1dab054..867faef6 100644 --- a/tests/TypeChecking/Generics/InvariantNullableUnionVarianceTest.php +++ b/tests/TypeChecking/Generics/InvariantNullableUnionVarianceTest.php @@ -137,6 +137,41 @@ function testAcceptCountableArrayAccessBox(InvariantVarianceBox $box): void { } +/** + * @param InvariantVarianceBox $box + */ +function testAcceptInvariantCountableBox(InvariantVarianceBox $box): void +{ +} + +/** + * @param InvariantVarianceBox<(Countable&ArrayAccess)|null> $box + */ +function testAcceptNullableCountableArrayAccessBox(InvariantVarianceBox $box): void +{ +} + +/** + * @param CovariantVarianceBox $box + */ +function testAcceptCovariantCountableArrayAccessBox(CovariantVarianceBox $box): void +{ +} + +/** + * @param CovariantVarianceBox $box + */ +function testAcceptCovariantCountableBox(CovariantVarianceBox $box): void +{ +} + +/** + * @param ContravariantVarianceBox $box + */ +function testAcceptContravariantCountableArrayAccessBox(ContravariantVarianceBox $box): void +{ +} + /** * @param InvariantVarianceBox $box */ @@ -210,6 +245,26 @@ function testAcceptContravariantDogBox(ContravariantVarianceBox $box): void return $animalBox; })->toThrow(TypeError::class, 'expects ' . InvariantVarianceBox::class); }); + + test('rejects invariant intersection widening (A&B&C -> A&B and A&B -> A)', function () { + /** @var InvariantVarianceBox $wideIntersectionBox */ + $wideIntersectionBox = new InvariantVarianceBox(); + + expect(fn () => testAcceptCountableArrayAccessBox($wideIntersectionBox)) + ->toThrow(TypeError::class, 'expects ' . InvariantVarianceBox::class) + ; + + expect(fn () => testAcceptNullableCountableArrayAccessBox($wideIntersectionBox)) + ->toThrow(TypeError::class, 'expects ' . InvariantVarianceBox::class) + ; + + /** @var InvariantVarianceBox $intersectionBox */ + $intersectionBox = new InvariantVarianceBox(); + + expect(fn () => testAcceptInvariantCountableBox($intersectionBox)) + ->toThrow(TypeError::class, 'expects ' . InvariantVarianceBox::class) + ; + }); }); describe('Preserves Pragmatic Subset Widening & Explicit Covariance/Contravariance', function () { @@ -240,9 +295,11 @@ function testAcceptContravariantDogBox(ContravariantVarianceBox $box): void $strBox = new InvariantVarianceBox(); testAcceptNullableArrayKeyBox($strBox); - /** @var InvariantVarianceBox $wideIntersectionBox */ - $wideIntersectionBox = new InvariantVarianceBox(); - testAcceptCountableArrayAccessBox($wideIntersectionBox); + /** @var InvariantVarianceBox $reorderedIntersectionBox */ + $reorderedIntersectionBox = new InvariantVarianceBox(); + testAcceptCountableArrayAccessBox($reorderedIntersectionBox); + testAcceptNullableCountableArrayAccessBox($reorderedIntersectionBox); + testAcceptBroadUpperBoundUnionBox($reorderedIntersectionBox); }); test('still permits class covariance under @template-covariant, use-site , and @template-contravariant', function () { @@ -258,6 +315,15 @@ function testAcceptContravariantDogBox(ContravariantVarianceBox $box): void $contraAnimalBox = new ContravariantVarianceBox(static fn (?Animal $a): mixed => null); testAcceptContravariantDogBox($contraAnimalBox); + /** @var CovariantVarianceBox $covWideIntersectionBox */ + $covWideIntersectionBox = new CovariantVarianceBox(); + testAcceptCovariantCountableArrayAccessBox($covWideIntersectionBox); + testAcceptCovariantCountableBox($covWideIntersectionBox); + + /** @var ContravariantVarianceBox $contraCountableBox */ + $contraCountableBox = new ContravariantVarianceBox(static fn (Countable $c): mixed => null); + testAcceptContravariantCountableArrayAccessBox($contraCountableBox); + expect(true)->toBeTrue(); }); }); From e1cf0a3451c4fd0c8a6ac8a98619fb8873976caf Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sat, 5 Dec 2026 21:55:08 +0800 Subject: [PATCH 24/24] Refactor ViolationCollector to enhance error message parsing; introduce methods for splitting phrases and add comprehensive tests for various violation scenarios. --- src/Internal/Reporting/ViolationCollector.php | 157 +++++++++++++++++- .../ViolationCollectorParsingTest.php | 151 +++++++++++++++++ 2 files changed, 301 insertions(+), 7 deletions(-) create mode 100644 tests/Internal/Reporting/ViolationCollectorParsingTest.php diff --git a/src/Internal/Reporting/ViolationCollector.php b/src/Internal/Reporting/ViolationCollector.php index b4affef6..f83b37af 100644 --- a/src/Internal/Reporting/ViolationCollector.php +++ b/src/Internal/Reporting/ViolationCollector.php @@ -935,12 +935,12 @@ private static function extractExpectedAndGiven(string $message): array if (preg_match('/Generic type argument (.+?) does not satisfy upper bound (.+?) of template ([a-zA-Z0-9_]+) in ([a-zA-Z0-9_\\\\]+)/', $message, $m) === 1) { return [trim($m[2]), 'type argument ' . trim($m[1]), trim($m[4])]; } - if (preg_match('/must be of type (.+?),\s*(.+?)\s*(?:given|returned)$/', $message, $m) === 1) { - return [trim($m[1]), trim($m[2]), null]; - } - if (preg_match('/must be (.+?),\s*(.+?)\s*(?:given|returned)$/', $message, $m) === 1) { - return [trim($m[1]), trim($m[2]), null]; + + $mustBeParsed = self::splitMustBePhrase($message); + if ($mustBeParsed !== null) { + return [$mustBeParsed[0], $mustBeParsed[1], null]; } + if (preg_match('/is missing required (?:key|property)\s*\'([^\']+)\'/', $message, $m) === 1) { return ["required '{$m[1]}'", 'missing', null]; } @@ -950,10 +950,153 @@ private static function extractExpectedAndGiven(string $message): array if (preg_match('/contains unexpected property\s*\'([^\']+)\'/', $message, $m) === 1) { return ['sealed shape', "unexpected property '{$m[1]}'", null]; } - if (preg_match('/expects (.+?),\s*but\s*(.+?)\s*was\s*(?:given|returned)/', $message, $m) === 1) { - return [trim($m[1]), trim($m[2]), null]; + + $expectsParsed = self::splitExpectsButPhrase($message); + if ($expectsParsed !== null) { + return [$expectsParsed[0], $expectsParsed[1], null]; } return ['', '', null]; } + + /** + * Splits "must be [of type] , given|returned" at the top-level comma. + * + * @return array{0: string, 1: string}|null + */ + private static function splitMustBePhrase(string $message): ?array + { + $pos = strpos($message, 'must be '); + if ($pos === false) { + return null; + } + + $prefixLen = str_starts_with(substr($message, $pos), 'must be of type ') ? 16 : 8; + $tail = substr($message, $pos + $prefixLen); + + if (preg_match('/\s+(?:given|returned)$/', $tail, $suffixMatch, PREG_OFFSET_CAPTURE) !== 1) { + return null; + } + + $body = substr($tail, 0, $suffixMatch[0][1]); + + return self::findTopLevelComma($body); + } + + /** + * Splits "expects , but was given|returned" at the top-level ", but " delimiter. + * + * @return array{0: string, 1: string}|null + */ + private static function splitExpectsButPhrase(string $message): ?array + { + $pos = strpos($message, 'expects '); + if ($pos === false) { + return null; + } + + $tail = substr($message, $pos + 8); + + if (preg_match('/\s+was\s+(?:given|returned)$/', $tail, $suffixMatch, PREG_OFFSET_CAPTURE) !== 1) { + return null; + } + + $body = substr($tail, 0, $suffixMatch[0][1]); + + return self::findTopLevelComma($body, requireBut: true); + } + + /** + * Scans a phrase for the first top-level comma outside quotes and balanced brackets/generics. + * + * @return array{0: string, 1: string}|null + */ + private static function findTopLevelComma(string $body, bool $requireBut = false): ?array + { + $len = \strlen($body); + $parenDepth = 0; + $braceDepth = 0; + $angleDepth = 0; + $bracketDepth = 0; + $inQuote = null; + + for ($i = 0; $i < $len; $i++) { + $char = $body[$i]; + + if ($inQuote !== null) { + if ($char === '\\' && $i + 1 < $len) { + $i++; + + continue; + } + + if ($char === $inQuote) { + $inQuote = null; + } + + continue; + } + + if ($char === '\'' || $char === '"') { + $inQuote = $char; + + continue; + } + + if ($char === '(') { + $parenDepth++; + } elseif ($char === ')') { + if ($parenDepth > 0) { + $parenDepth--; + } + } elseif ($char === '{') { + $braceDepth++; + } elseif ($char === '}') { + if ($braceDepth > 0) { + $braceDepth--; + } + } elseif ($char === '[') { + $bracketDepth++; + } elseif ($char === ']') { + if ($bracketDepth > 0) { + $bracketDepth--; + } + } elseif ($char === '<') { + if ($i + 1 < $len && $body[$i + 1] === '=') { + $i++; + + continue; + } + $angleDepth++; + } elseif ($char === '>') { + $prev = $i > 0 ? $body[$i - 1] : ''; + if ($prev !== '=' && $prev !== '-' && $angleDepth > 0) { + $angleDepth--; + } + } elseif ( + $char === ',' + && $parenDepth === 0 + && $braceDepth === 0 + && $angleDepth === 0 + && $bracketDepth === 0 + ) { + $left = trim(substr($body, 0, $i)); + $right = substr($body, $i + 1); + + if (! $requireBut) { + $rightTrimmed = trim($right); + if ($left !== '' && $rightTrimmed !== '') { + return [$left, $rightTrimmed]; + } + } elseif (preg_match('/^\s*but\s+(.+)$/s', $right, $m) === 1) { + $rightTrimmed = trim($m[1]); + if ($left !== '' && $rightTrimmed !== '') { + return [$left, $rightTrimmed]; + } + } + } + } + + return null; + } } diff --git a/tests/Internal/Reporting/ViolationCollectorParsingTest.php b/tests/Internal/Reporting/ViolationCollectorParsingTest.php new file mode 100644 index 00000000..5d0362ec --- /dev/null +++ b/tests/Internal/Reporting/ViolationCollectorParsingTest.php @@ -0,0 +1,151 @@ + 'report']); + }); + + afterEach(function () { + ViolationCollector::reset(); + Config::reset(); + }); + + test('preserves multi-argument generic types inside unions when both expected and given contain commas', function () { + $msg1 = 'Noctud\\Collection\\Map\\HashMap\\HashKeyValueStore::random(): Return value must be of type (Noctud\\Collection\\Map\\SimpleMapEntry | null), Noctud\\Collection\\Map\\SimpleMapEntry returned'; + ViolationCollector::handle(new ErrorMessage($msg1), 'return', null, __FILE__, 10); + + $msg2 = 'Noctud\\Collection\\Tests\\Map\\StringMap\\Unit\\ImmutableStringMapTest::createCowCollection(): Return value must be of type (Noctud\\Collection\\Collection | Noctud\\Collection\\Map\\Map<(int | string), string>), Noctud\\Collection\\Map\\StringMap\\ImmutableStringMap returned'; + ViolationCollector::handle(new ErrorMessage($msg2), 'return', null, __FILE__, 20); + + $violations = ViolationCollector::getViolations(); + + expect($violations)->toHaveCount(2); + expect($violations[0]->expected)->toBe('(Noctud\\Collection\\Map\\SimpleMapEntry | null)'); + expect($violations[0]->given)->toBe('Noctud\\Collection\\Map\\SimpleMapEntry'); + + expect($violations[1]->expected)->toBe('(Noctud\\Collection\\Collection | Noctud\\Collection\\Map\\Map<(int | string), string>)'); + expect($violations[1]->given)->toBe('Noctud\\Collection\\Map\\StringMap\\ImmutableStringMap'); + }); + + test('preserves array shapes, object shapes, callables, and int ranges containing commas', function () { + ViolationCollector::handle( + new ErrorMessage('testFn(): Argument $x must be of type (array{a: int, b: string} | object{x: int, y: int}), int (42) given'), + 'parameter', + null, + __FILE__, + 30 + ); + + ViolationCollector::handle( + new ErrorMessage("testFn(): Argument \$cb must be of type (callable(int, string): bool | null), string 'hello, world' given"), + 'parameter', + null, + __FILE__, + 31 + ); + + ViolationCollector::handle( + new ErrorMessage('testFn(): Argument $n must be of type (int<1, 10> | string), bool (false) given'), + 'parameter', + null, + __FILE__, + 32 + ); + + $violations = ViolationCollector::getViolations(); + + expect($violations)->toHaveCount(3); + expect($violations[0]->expected)->toBe('(array{a: int, b: string} | object{x: int, y: int})'); + expect($violations[0]->given)->toBe('int (42)'); + + expect($violations[1]->expected)->toBe('(callable(int, string): bool | null)'); + expect($violations[1]->given)->toBe("string 'hello, world'"); + + expect($violations[2]->expected)->toBe('(int<1, 10> | string)'); + expect($violations[2]->given)->toBe('bool (false)'); + }); + + test('preserves quoted literal values containing commas', function () { + ViolationCollector::handle( + new ErrorMessage("testFn(): Argument \$a must be literal 'a, b', string 'c, d' given"), + 'parameter', + null, + __FILE__, + 40 + ); + + ViolationCollector::handle( + new ErrorMessage("testFn(): Argument \$b must be of type ('a, b' | 'c, d'), string 'x, y' given"), + 'parameter', + null, + __FILE__, + 41 + ); + + $violations = ViolationCollector::getViolations(); + + expect($violations)->toHaveCount(2); + expect($violations[0]->expected)->toBe("literal 'a, b'"); + expect($violations[0]->given)->toBe("string 'c, d'"); + + expect($violations[1]->expected)->toBe("('a, b' | 'c, d')"); + expect($violations[1]->given)->toBe("string 'x, y'"); + }); + + test('parses <= and >= range bounds, expects/but messages, and simple types accurately', function () { + ViolationCollector::handle( + new ErrorMessage('testFn(): Argument $n must be <= 10, 99 given'), + 'parameter', + null, + __FILE__, + 50 + ); + + ViolationCollector::handle( + new ErrorMessage('testFn(): Argument $n must be >= 1, -5 given'), + 'parameter', + null, + __FILE__, + 51 + ); + + ViolationCollector::handle( + new ErrorMessage("testFn(): Return value expects Box, but Box<'c, d'> was returned"), + 'return', + null, + __FILE__, + 52 + ); + + ViolationCollector::handle( + new ErrorMessage('testFn(): Return value must be of type int, none returned'), + 'return', + null, + __FILE__, + 53 + ); + + $violations = ViolationCollector::getViolations(); + + expect($violations)->toHaveCount(4); + expect($violations[0]->expected)->toBe('<= 10'); + expect($violations[0]->given)->toBe('99'); + + expect($violations[1]->expected)->toBe('>= 1'); + expect($violations[1]->given)->toBe('-5'); + + expect($violations[2]->expected)->toBe("Box"); + expect($violations[2]->given)->toBe("Box<'c, d'>"); + + expect($violations[3]->expected)->toBe('int'); + expect($violations[3]->given)->toBe('none'); + }); +});