From 22b4a7f7e65db9812d84a55208d200152a3365e4 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Fri, 6 Nov 2026 16:35:33 +0800 Subject: [PATCH 01/11] Enhance template handling by adding default type checks and applying class template defaults and able to get the generic type without annoating it manually --- src/Internal/Checker/ParamChecker.php | 4 + src/Internal/Generics/TemplateManager.php | 69 +++++- tests/Fixtures/Generics/MultiTemplateBag.php | 4 +- .../Generics/DefaultTemplateTypesTest.php | 196 ++++++++++++++++-- 4 files changed, 256 insertions(+), 17 deletions(-) diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index c0e8d764..8b9bd213 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -312,6 +312,10 @@ private static function prepareGenericBindings( $targetClass = \is_string($thisOrClass) && $thisOrClass !== '' ? $thisOrClass : $declaringClass; TemplateManager::getClassInheritedBindings($targetClass); } + + if ($thisObj !== null && ! str_ends_with(strtolower($effectiveFunction), '::__construct')) { + TemplateManager::applyClassTemplateDefaults($thisObj, $classTemplates); + } } } diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index f98ebf09..9ab7b5c4 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -696,11 +696,24 @@ public static function getBoundTemplatesForInstance(object $instance): array { self::ensureInstanceInherited($instance); - if (self::$instanceTemplateBindings !== null && isset(self::$instanceTemplateBindings[$instance])) { - return self::$instanceTemplateBindings[$instance]; + $bindings = (self::$instanceTemplateBindings !== null && isset(self::$instanceTemplateBindings[$instance])) + ? self::$instanceTemplateBindings[$instance] + : []; + + try { + $ref = new \ReflectionClass($instance); + [$hierarchyTemplates] = self::collectHierarchyTemplatesAndVariances($ref); + + foreach ($hierarchyTemplates as $tName => $templateTag) { + if (! isset($bindings[$tName]) && $templateTag->default !== null && ! self::isUnspecializedDefault($templateTag)) { + $bindings[$tName] = $templateTag->default; + } + } + } catch (\Throwable $e) { + // Silently ignore reflection errors } - return []; + return $bindings; } /** @@ -925,6 +938,56 @@ public static function bindInstanceFromNode(object $instance, GenericTypeNode $t return null; } + /** + * Checks whether a template's default type is an unspecialized placeholder (e.g. mixed or repeating its own bound). + */ + public static function isUnspecializedDefault(TemplateTagValueNode $templateTag): bool + { + if ($templateTag->default === null) { + return true; + } + + if ($templateTag->default instanceof IdentifierTypeNode) { + if (strtolower($templateTag->default->name) === 'mixed') { + return true; + } + } + + if ($templateTag->bound !== null && (string) $templateTag->default === (string) $templateTag->bound) { + return true; + } + + return false; + } + + /** + * Binds declared default template types onto an instance for any template not yet bound. + * + * @param array $classTemplates + */ + public static function applyClassTemplateDefaults(object $instance, array $classTemplates): void + { + if ($classTemplates === []) { + return; + } + + self::ensureInstanceInherited($instance); + self::$instanceTemplateBindings ??= new WeakMap(); + $bindings = self::$instanceTemplateBindings[$instance] ?? []; + $changed = false; + + foreach ($classTemplates as $tName => $templateTag) { + if (! isset($bindings[$tName]) && $templateTag->default !== null && ! self::isUnspecializedDefault($templateTag)) { + $bindings[$tName] = $templateTag->default; + $changed = true; + } + } + + if ($changed) { + self::$instanceTemplateBindings[$instance] = $bindings; + } + } + /** * @param \ReflectionClass $ref * diff --git a/tests/Fixtures/Generics/MultiTemplateBag.php b/tests/Fixtures/Generics/MultiTemplateBag.php index 0b73fded..6994aada 100644 --- a/tests/Fixtures/Generics/MultiTemplateBag.php +++ b/tests/Fixtures/Generics/MultiTemplateBag.php @@ -5,8 +5,8 @@ namespace TypePHP\Tests\Fixtures\Generics; /** - * @template K of array-key = string - * @template V = int + * @template K of array-key + * @template V */ class MultiTemplateBag { diff --git a/tests/TypeChecking/Generics/DefaultTemplateTypesTest.php b/tests/TypeChecking/Generics/DefaultTemplateTypesTest.php index da842745..cf065bf2 100644 --- a/tests/TypeChecking/Generics/DefaultTemplateTypesTest.php +++ b/tests/TypeChecking/Generics/DefaultTemplateTypesTest.php @@ -2,7 +2,9 @@ declare(strict_types=1); +use TypePHP\Exception\TypeError; use TypePHP\Tests\Fixtures\Domain\Dog; +use TypePHP\TypePHP; /** * 1. Default template without explicit bound (@template T = string) @@ -32,22 +34,192 @@ function testDefaultTemplateObject(mixed $value): mixed return $value; } +/** + * 3. Class with default template type (@template T = int) and no constructor + * + * @template T = int + */ +class DefaultIntBox +{ + /** + * @var list + */ + public array $items = []; + + /** + * @param T $item + */ + public function add(mixed $item): void + { + $this->items[] = $item; + } +} + +/** + * 4. Class with default template type (@template T = int) and optional constructor parameter + * + * @template T = int + */ +class DefaultBoxWithCtor +{ + /** + * @var T|null + */ + public mixed $value = null; + + /** + * @param T|null $initial + */ + public function __construct(mixed $initial = null) + { + $this->value = $initial; + } + + /** + * @param T $val + */ + public function set(mixed $val): void + { + $this->value = $val; + } +} + +/** + * 5. Multi-template class with partial default (@template K of array-key = string, @template V) + * + * @template K of array-key = string + * @template V + */ +class PartialDefaultMap +{ + /** + * @var array + */ + public array $entries = []; + + /** + * @param K $key + * @param V $val + */ + public function put(mixed $key, mixed $val): void + { + $this->entries[$key] = $val; + } +} + describe('Default Template Annotations (@template T = DefaultType)', function () { - test('uses default template type string when template T is unbound', function () { - expect(testDefaultTemplateString('hello'))->toBe('hello'); + describe('1. Standalone Function Default Templates', function () { + test('uses default template type string when template T is unbound', function () { + expect(testDefaultTemplateString('hello'))->toBe('hello'); - expect(fn () => testDefaultTemplateString(12345)) - ->toThrow(TypeError::class, 'Return value') - ; + expect(fn () => testDefaultTemplateString(12345)) + ->toThrow(TypeError::class, 'Return value') + ; + }); + + test('uses default template type stdClass when template has both bound and default', function () { + $std = new stdClass(); + expect(testDefaultTemplateObject($std))->toBe($std); + + expect(fn () => testDefaultTemplateObject(new Dog())) + ->toThrow(TypeError::class, 'Return value') + ; + }); }); - test('uses default template type stdClass when template has both bound and default', function () { - $std = new stdClass(); - expect(testDefaultTemplateObject($std))->toBe($std); + describe('2. Unannotated Class Instantiation with Default Template (@template T = int)', function () { + test('records default template type on unannotated instance in getGenericTypes and getGenericType', function () { + $box = new DefaultIntBox(); + + expect(TypePHP::getGenericTypes($box))->toBe(['T' => 'int']) + ->and(TypePHP::getGenericType($box))->toBe('int') + ; + }); + + test('enforces default template type on method calls and property mutations for unannotated instance', function () { + $freshBox = new DefaultIntBox(); + + expect(fn () => $freshBox->add('not_an_int')) + ->toThrow(TypeError::class, 'must be of type int') + ; + + $box = new DefaultIntBox(); + $box->add(42); + expect($box->items)->toBe([42]); + + expect(fn () => $box->add('not_an_int')) + ->toThrow(TypeError::class, 'must be of type int') + ; + + expect(function () use ($box) { + $box->items[] = 'not_an_int'; + })->toThrow(TypeError::class, 'must be of type int'); + }); + + test('allows @var annotation to override the default template type', function () { + /** @var DefaultIntBox $stringBox */ + $stringBox = new DefaultIntBox(); + + expect(TypePHP::getGenericTypes($stringBox))->toBe(['T' => 'string']) + ->and(TypePHP::getGenericType($stringBox))->toBe('string') + ; + + $stringBox->add('hello'); + expect($stringBox->items)->toBe(['hello']); + + expect(fn () => $stringBox->add(42)) + ->toThrow(TypeError::class, 'must be of type string') + ; + }); + }); + + describe('3. Constructor Inference vs Default Template Fallback', function () { + test('falls back to default T = int when constructor is called with no arguments', function () { + $box = new DefaultBoxWithCtor(); + + expect(TypePHP::getGenericTypes($box))->toBe(['T' => 'int']); + + $box->set(100); + expect($box->value)->toBe(100); + + expect(fn () => $box->set('wrong')) + ->toThrow(TypeError::class, 'must be of type int') + ; + }); + + test('overrides default T = int when constructor argument infers T = string', function () { + $box = new DefaultBoxWithCtor('initial_string'); + + expect(TypePHP::getGenericTypes($box))->toBe(['T' => 'string']); + + $box->set('updated_string'); + expect($box->value)->toBe('updated_string'); + + expect(fn () => $box->set(100)) + ->toThrow(TypeError::class, 'must be of type string') + ; + }); + }); + + describe('4. Partial Defaults on Multi-Template Classes', function () { + test('records K = string default on instantiation and infers V on first method call', function () { + $map = new PartialDefaultMap(); + + expect(TypePHP::getGenericTypes($map))->toBe(['K' => 'string']); + + expect(fn () => $map->put(123, 'value')) + ->toThrow(TypeError::class, 'must be of type string') + ; + + $map->put('first_key', 42); + + expect(TypePHP::getGenericTypes($map))->toBe([ + 'K' => 'string', + 'V' => 'int', + ]); - // Dog is an object (satisfies bound 'object'), but NOT stdClass (violates default 'stdClass') - expect(fn () => testDefaultTemplateObject(new Dog())) - ->toThrow(TypeError::class, 'Return value') - ; + expect(fn () => $map->put('second_key', 'not_an_int')) + ->toThrow(TypeError::class, 'must be of type int'); + }); }); }); From 7d4dd65026ce7d2518e2143b460fa00b72ccb7ea Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Fri, 6 Nov 2026 17:26:21 +0800 Subject: [PATCH 02/11] Enhance conditional type handling in ParamOutChecker and DefaultTemplateTypesTest with new tests for default templates and conditional parameters --- src/Internal/Checker/ConditionalChecker.php | 13 +- src/Internal/Checker/ParamOutChecker.php | 8 + .../Generics/DefaultTemplateTypesTest.php | 238 +++++++++++++++++- 3 files changed, 253 insertions(+), 6 deletions(-) diff --git a/src/Internal/Checker/ConditionalChecker.php b/src/Internal/Checker/ConditionalChecker.php index e09f5b0b..ebc776e3 100644 --- a/src/Internal/Checker/ConditionalChecker.php +++ b/src/Internal/Checker/ConditionalChecker.php @@ -293,8 +293,17 @@ public static function resolveTemplateConditional( string $function = '' ): TypeNode { $subjectTypeNode = $node->subjectType; - if ($subjectTypeNode instanceof IdentifierTypeNode && isset($boundTemplates[$subjectTypeNode->name])) { - $subjectTypeNode = $boundTemplates[$subjectTypeNode->name]; + if ($subjectTypeNode instanceof IdentifierTypeNode) { + if (isset($boundTemplates[$subjectTypeNode->name])) { + $subjectTypeNode = $boundTemplates[$subjectTypeNode->name]; + } elseif ($function !== '') { + $contract = DocblockParser::parse($function); + $allTemplates = $contract['allTemplates'] ?? [...($contract['classTemplates'] ?? []), ...($contract['templates'] ?? [])]; + if (isset($allTemplates[$subjectTypeNode->name])) { + $templateTag = $allTemplates[$subjectTypeNode->name]; + $subjectTypeNode = $templateTag->default ?? $templateTag->bound ?? $subjectTypeNode; + } + } } $isTargetMatch = TemplateManager::checkVariance($subjectTypeNode, $node->targetType, GenericTypeNode::VARIANCE_COVARIANT); diff --git a/src/Internal/Checker/ParamOutChecker.php b/src/Internal/Checker/ParamOutChecker.php index 4dd10ff1..040e17e2 100644 --- a/src/Internal/Checker/ParamOutChecker.php +++ b/src/Internal/Checker/ParamOutChecker.php @@ -78,11 +78,19 @@ public static function checkParamOut( ? TemplateManager::getBoundTemplates($effectiveFunction, $thisObj, $allTemplates) : []; + if (ConditionalChecker::containsConditional($typeNode)) { + $typeNode = ConditionalChecker::resolve($typeNode, [], $boundTemplates, $registry, $effectiveFunction); + } + if (\count($boundTemplates) > 0 || \count($allTemplates) > 0) { $typeNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $allTemplates); } $typeNode = SpecialTypeResolver::resolve($typeNode, $effectiveFunction, $thisObj); + if (ConditionalChecker::containsConditional($typeNode)) { + $typeNode = ConditionalChecker::resolve($typeNode, [], $boundTemplates, $registry, $effectiveFunction); + } + $context = $effectiveFunction . '(): Argument &$' . $paramName . ' (param-out)'; $err = $registry->validate($value, $typeNode, $context); diff --git a/tests/TypeChecking/Generics/DefaultTemplateTypesTest.php b/tests/TypeChecking/Generics/DefaultTemplateTypesTest.php index cf065bf2..c3c5d329 100644 --- a/tests/TypeChecking/Generics/DefaultTemplateTypesTest.php +++ b/tests/TypeChecking/Generics/DefaultTemplateTypesTest.php @@ -35,7 +35,51 @@ function testDefaultTemplateObject(mixed $value): mixed } /** - * 3. Class with default template type (@template T = int) and no constructor + * 3. Standalone function with default template in conditional return + * + * @template T = int + * + * @param T|null $sample + * @param mixed $returnValue + * + * @return (T is int ? positive-int : non-empty-string) + */ +function testDefaultTemplateConditionalReturn(mixed $sample = null, mixed $returnValue = null): mixed +{ + return $returnValue; +} + +/** + * 4. Standalone function with default template in conditional parameter + * + * @template T = int + * + * @param (T is int ? positive-int : non-empty-string) $payload + * @param T|null $sample + */ +function testDefaultTemplateConditionalParam(mixed $payload, mixed $sample = null): mixed +{ + return $payload; +} + +/** + * 5. Standalone function with default template in conditional @param-out + * + * @template T = int + * + * @param mixed &$out + * @param mixed $newValue + * @param T|null $sample + * + * @param-out (T is int ? positive-int : non-empty-string) $out + */ +function testDefaultTemplateConditionalParamOut(mixed &$out, mixed $newValue, mixed $sample = null): void +{ + $out = $newValue; +} + +/** + * 6. Class with default template type (@template T = int) and no constructor * * @template T = int */ @@ -53,10 +97,64 @@ public function add(mixed $item): void { $this->items[] = $item; } + + /** + * Zero-parameter method with conditional return based on class template T + * + * @return (T is int ? positive-int : non-empty-string) + */ + public function getDefaultConditionalValue(mixed $val): mixed + { + return $this->computeConditional($val); + } + + /** + * @return (T is int ? positive-int : non-empty-string) + */ + public function computeOne(): mixed + { + return 42; + } + + /** + * @return (T is int ? positive-int : non-empty-string) + */ + public function computeInvalidNegative(): mixed + { + return -10; + } + + /** + * @param mixed &$out + * + * @param-out T $out + */ + public function exportTo(mixed &$out, mixed $val): void + { + $out = $val; + } + + /** + * @param mixed &$out + * + * @param-out (T is int ? positive-int : non-empty-string) $out + */ + public function exportConditionalTo(mixed &$out, mixed $val): void + { + $out = $val; + } + + /** + * @return (T is int ? positive-int : non-empty-string) + */ + private function computeConditional(mixed $val): mixed + { + return $val; + } } /** - * 4. Class with default template type (@template T = int) and optional constructor parameter + * 7. Class with default template type (@template T = int) and optional constructor parameter * * @template T = int */ @@ -85,7 +183,7 @@ public function set(mixed $val): void } /** - * 5. Multi-template class with partial default (@template K of array-key = string, @template V) + * 8. Multi-template class with partial default (@template K of array-key = string, @template V) * * @template K of array-key = string * @template V @@ -121,6 +219,7 @@ public function put(mixed $key, mixed $val): void $std = new stdClass(); expect(testDefaultTemplateObject($std))->toBe($std); + // Dog is an object (satisfies bound 'object'), but NOT stdClass (violates default 'stdClass') expect(fn () => testDefaultTemplateObject(new Dog())) ->toThrow(TypeError::class, 'Return value') ; @@ -139,6 +238,7 @@ public function put(mixed $key, mixed $val): void test('enforces default template type on method calls and property mutations for unannotated instance', function () { $freshBox = new DefaultIntBox(); + // Must reject string even on the very first method call before any valid int is added! expect(fn () => $freshBox->add('not_an_int')) ->toThrow(TypeError::class, 'must be of type int') ; @@ -207,6 +307,7 @@ public function put(mixed $key, mixed $val): void expect(TypePHP::getGenericTypes($map))->toBe(['K' => 'string']); + // Key must already be enforced as string even on the first call! expect(fn () => $map->put(123, 'value')) ->toThrow(TypeError::class, 'must be of type string') ; @@ -219,7 +320,136 @@ public function put(mixed $key, mixed $val): void ]); expect(fn () => $map->put('second_key', 'not_an_int')) - ->toThrow(TypeError::class, 'must be of type int'); + ->toThrow(TypeError::class, 'must be of type int') + ; + }); + }); + + describe('5. Conditional Types with Default Templates (T is Target ? A : B)', function () { + test('evaluates true branch (positive-int) on standalone function when T falls back to default int', function () { + expect(testDefaultTemplateConditionalReturn(null, 42))->toBe(42); + + expect(fn () => testDefaultTemplateConditionalReturn(null, -10)) + ->toThrow(TypeError::class, 'positive-int') + ; + + expect(fn () => testDefaultTemplateConditionalReturn(null, 'string_val')) + ->toThrow(TypeError::class, 'positive-int') + ; + }); + + test('evaluates else branch (non-empty-string) on standalone function when T is overridden to string', function () { + expect(testDefaultTemplateConditionalReturn('override', 'valid_string'))->toBe('valid_string'); + + expect(fn () => testDefaultTemplateConditionalReturn('override', '')) + ->toThrow(TypeError::class, 'non-empty-string') + ; + }); + + test('evaluates conditional parameter using default T = int when sample is omitted', function () { + expect(testDefaultTemplateConditionalParam(42))->toBe(42); + + expect(fn () => testDefaultTemplateConditionalParam(-5)) + ->toThrow(TypeError::class, 'positive-int') + ; + + expect(fn () => testDefaultTemplateConditionalParam('not_int')) + ->toThrow(TypeError::class, 'positive-int') + ; + }); + + test('evaluates conditional return on zero-parameter class methods using class default T = int', function () { + $box = new DefaultIntBox(); + + expect($box->computeOne())->toBe(42); + + expect(fn () => $box->computeInvalidNegative()) + ->toThrow(TypeError::class, 'positive-int') + ; + + expect($box->getDefaultConditionalValue(100))->toBe(100); + + expect(fn () => $box->getDefaultConditionalValue(-50)) + ->toThrow(TypeError::class, 'positive-int') + ; + }); + + test('evaluates else branch on class conditional return when default is overridden via @var DefaultIntBox', function () { + /** @var DefaultIntBox $stringBox */ + $stringBox = new DefaultIntBox(); + + expect($stringBox->getDefaultConditionalValue('hello'))->toBe('hello'); + + expect(fn () => $stringBox->getDefaultConditionalValue('')) + ->toThrow(TypeError::class, 'non-empty-string') + ; + }); + }); + + describe('6. @param-out with Default Templates & Conditional @param-out', function () { + test('enforces default T = int on @param-out T $out for unannotated class instance', function () { + $box = new DefaultIntBox(); + $out = null; + + $box->exportTo($out, 99); + expect($out)->toBe(99); + + expect(fn () => $box->exportTo($out, 'not_an_int')) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type int') + ; + }); + + test('enforces overridden T = string on @param-out T $out when pre-bound via @var', function () { + /** @var DefaultIntBox $stringBox */ + $stringBox = new DefaultIntBox(); + $out = null; + + $stringBox->exportTo($out, 'valid_str'); + expect($out)->toBe('valid_str'); + + expect(fn () => $stringBox->exportTo($out, 12345)) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type string') + ; + }); + + test('enforces conditional @param-out (T is int ? positive-int : non-empty-string) on class method', function () { + $box = new DefaultIntBox(); + $out = null; + + $box->exportConditionalTo($out, 50); + expect($out)->toBe(50); + + expect(fn () => $box->exportConditionalTo($out, -20)) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type positive-int') + ; + + /** @var DefaultIntBox $stringBox */ + $stringBox = new DefaultIntBox(); + $stringBox->exportConditionalTo($out, 'active'); + expect($out)->toBe('active'); + + expect(fn () => $stringBox->exportConditionalTo($out, '')) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type non-empty-string') + ; + }); + + test('enforces conditional @param-out on standalone function with default T = int', function () { + $out = null; + + testDefaultTemplateConditionalParamOut($out, 100); + expect($out)->toBe(100); + + expect(fn () => testDefaultTemplateConditionalParamOut($out, -5)) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type positive-int') + ; + + // Overriding T = string by passing 'sample_str' + testDefaultTemplateConditionalParamOut($out, 'hello', 'sample_str'); + expect($out)->toBe('hello'); + + expect(fn () => testDefaultTemplateConditionalParamOut($out, '', 'sample_str')) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type non-empty-string') + ; }); }); }); From 95dc477e6ae200b3aff410742b0b6bd3cf1bcb5e Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Fri, 6 Nov 2026 17:54:11 +0800 Subject: [PATCH 03/11] Enhance F-bounded polymorphism tests with new generic holder and parameter type checks --- src/Internal/Checker/ParamChecker.php | 14 +-- .../Generics/FBoundedPolymorphismTest.php | 100 +++++++++++++++++- 2 files changed, 103 insertions(+), 11 deletions(-) diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index 8b9bd213..63362fdd 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -421,7 +421,7 @@ private static function validateAllParameters( } } - if (\count($allTemplates) > 1) { + if (\count($allTemplates) > 0) { return self::validateCrossReferencedTemplateBounds( $contractTypes, $baseTypes, @@ -655,7 +655,7 @@ private static function extractCallableNodes(array $types): array } /** - * Re-validates template upper bounds that reference other sibling templates once all parameters have been bound. + * Re-validates template upper bounds that reference templates (F-bounds and cross-template bounds) once all parameters have been bound. * * @param array $contractTypes * @param array $baseTypes @@ -684,17 +684,13 @@ private static function validateCrossReferencedTemplateBounds( continue; } - $otherTemplates = $allTemplates; - unset($otherTemplates[$tName]); - - if (! DocblockParser::typeReferencesTemplate($templateNode->bound, $otherTemplates)) { + if (! DocblockParser::typeReferencesTemplate($templateNode->bound, $allTemplates)) { continue; } $substitutedBound = TemplateSubstitutor::substitute($templateNode->bound, $finalBoundTemplates); $resolvedBound = SpecialTypeResolver::resolve($substitutedBound, $effectiveFunction, $thisObj); - $matchedParam = false; foreach ($contractTypes as $paramName => $_) { if (! isset($vars[$paramName]) && ! \array_key_exists($paramName, $vars)) { continue; @@ -705,7 +701,6 @@ private static function validateCrossReferencedTemplateBounds( $isSensitive = $sensitiveParams[$paramName] ?? false; if ($baseType instanceof GenericTypeNode && self::isClassStringTemplate($baseType, [$tName => $templateNode])) { - $matchedParam = true; if (\is_string($val) && ! self::checkClassStringSatisfiesBound($val, $resolvedBound)) { $redact = $isSensitive || Config::isRedactValuesEnabled(); $boundDisplay = (string) $resolvedBound; @@ -714,7 +709,6 @@ private static function validateCrossReferencedTemplateBounds( return ErrorFactory::createError($effectiveFunction . '(): Argument $' . $paramName . ' (class-string<' . $tName . '>) must be a class-string of ' . $boundDisplay . ', ' . $displayVal); } } elseif (self::getTemplateName($baseType, [$tName => $templateNode]) === $tName) { - $matchedParam = true; $sampleVal = ($baseType instanceof ArrayTypeNode && \is_array($val)) ? ($val[0] ?? null) : $val; if ($sampleVal !== null) { $err = $registry->validate($sampleVal, $resolvedBound, $effectiveFunction . '(): Argument $' . $paramName . ' (template ' . $tName . ')', $isSensitive); @@ -725,7 +719,7 @@ private static function validateCrossReferencedTemplateBounds( } } - if (! $matchedParam && ! TemplateManager::checkVariance($finalBoundTemplates[$tName], $resolvedBound, GenericTypeNode::VARIANCE_COVARIANT)) { + if (! TemplateManager::checkVariance($finalBoundTemplates[$tName], $resolvedBound, GenericTypeNode::VARIANCE_COVARIANT)) { return ErrorFactory::createError( $effectiveFunction . "(): Generic type argument {$finalBoundTemplates[$tName]} does not satisfy upper bound {$resolvedBound} of template {$tName}" ); diff --git a/tests/TypeChecking/Generics/FBoundedPolymorphismTest.php b/tests/TypeChecking/Generics/FBoundedPolymorphismTest.php index 2d879346..18f553d5 100644 --- a/tests/TypeChecking/Generics/FBoundedPolymorphismTest.php +++ b/tests/TypeChecking/Generics/FBoundedPolymorphismTest.php @@ -4,6 +4,7 @@ namespace TypePHP\Tests\TypeChecking\Generics; +use Closure; use TypePHP\Exception\TypeError; /** @@ -57,6 +58,21 @@ public function __construct(public int $v) } } +/** + * Unbounded generic holder to test F-bound inference from generic objects + * + * @template T + */ +final class FBoundHolder +{ + /** + * @param T $item + */ + public function __construct(public mixed $item) + { + } +} + /** * Raw min without docblock contract */ @@ -81,6 +97,54 @@ function fBoundMin(FBoundComparable $a, FBoundComparable $b): FBoundComparable return $a->compareTo($b) <= 0 ? $a : $b; } +/** + * F-Bounded template inside a generic list parameter + * + * @template T of FBoundComparable + * + * @param list $items + */ +function fBoundAcceptList(array $items): bool +{ + return true; +} + +/** + * F-Bounded template inside an array shape parameter + * + * @template T of FBoundComparable + * + * @param array{item: T} $payload + */ +function fBoundAcceptShape(array $payload): bool +{ + return true; +} + +/** + * F-Bounded template inferred from a Closure parameter typehint + * + * @template T of FBoundComparable + * + * @param Closure(T): int $callback + */ +function fBoundAcceptClosure(Closure $callback): bool +{ + return true; +} + +/** + * F-Bounded template inferred from a Generic Object parameter + * + * @template T of FBoundComparable + * + * @param FBoundHolder $holder + */ +function fBoundAcceptHolder(FBoundHolder $holder): bool +{ + return true; +} + /** * C#: class AGenericClass where T : IComparable * @@ -268,4 +332,38 @@ public function compareTo(mixed $other): int ); }); }); -}); + + describe('4. F-Bounds in Compound Parameter Types (Lists, Shapes, Closures & Generic Objects)', function () { + test('accepts valid FBoundNum and rejects FBoundRogue inside list parameter', function () { + expect(fBoundAcceptList([new FBoundNum(1), new FBoundNum(2)]))->toBeTrue(); + + expect(fn () => fBoundAcceptList([new FBoundRogue()])) + ->toThrow(TypeError::class) + ; + }); + + test('accepts valid FBoundNum and rejects FBoundRogue inside array shape parameter', function () { + expect(fBoundAcceptShape(['item' => new FBoundNum(10)]))->toBeTrue(); + + expect(fn () => fBoundAcceptShape(['item' => new FBoundRogue()])) + ->toThrow(TypeError::class) + ; + }); + + test('accepts valid FBoundNum and rejects FBoundRogue in Closure(T) parameter typehint', function () { + expect(fBoundAcceptClosure(fn (FBoundNum $n): int => $n->value))->toBeTrue(); + + expect(fn () => fBoundAcceptClosure(fn (FBoundRogue $r): int => $r->id)) + ->toThrow(TypeError::class) + ; + }); + + test('accepts valid FBoundNum and rejects FBoundRogue inside Generic Object FBoundHolder parameter', function () { + expect(fBoundAcceptHolder(new FBoundHolder(new FBoundNum(5))))->toBeTrue(); + + expect(fn () => fBoundAcceptHolder(new FBoundHolder(new FBoundRogue()))) + ->toThrow(TypeError::class) + ; + }); + }); +}); \ No newline at end of file From 70e0fb1783135b866f457dbd19f7f14976bc0838 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Fri, 6 Nov 2026 18:10:46 +0800 Subject: [PATCH 04/11] Enhance param-out handling with conditional checks and additional tests for parameter-based contracts --- src/Internal/Ast/FunctionContractInjector.php | 59 +++-- src/Internal/Checker/ParamOutChecker.php | 12 +- src/Internal/RuntimeTypeChecker.php | 15 +- .../Boundaries/ParamOutContractsTest.php | 219 +++++++++++------- 4 files changed, 198 insertions(+), 107 deletions(-) diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index a7fdad3a..b5d3587a 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -115,7 +115,7 @@ public static function inject( $hasSelfOut = $isClassMethod && ! $node->isStatic() && ($hasSelfOutDoc || ($hasClassTemplates && $hasRealInheritance)); $hasParam = ($isMagicGet || $isMagicCall) || ($paramCount > 0 && ( - str_contains($docText, ' is ') || (($hasReturnDoc || $hasSelfOutDoc) && str_contains($docText, '$')) + str_contains($docText, ' is ') || (($hasReturnDoc || $hasSelfOutDoc || $hasParamOutDoc) && str_contains($docText, '$')) )) || self::hasParamContracts( $docText, $isClassMethod, @@ -406,7 +406,7 @@ private static function resolveThisArg(bool $isClassMethod, Node\Stmt\Function_| private static function isGenerator(Node\Stmt\Function_|Node\Stmt\ClassMethod $node): bool { - $visitor = new class () extends NodeVisitorAbstract { + $visitor = new class() extends NodeVisitorAbstract { public bool $isGen = false; public function enterNode(Node $n): ?int @@ -552,8 +552,15 @@ private static function buildSetupScopeStmt(array $params, Node\Expr $thisArg, b * * @return array */ - public static function buildParamOutCheckStmts(array $byRefParamNames, Node\Expr $thisArg): array - { + public static function buildParamOutCheckStmts( + array $byRefParamNames, + Node\Expr $thisArg, + bool $needsReturnVars = false + ): array { + $varsArg = $needsReturnVars + ? new Node\Expr\Variable('_typephpArgs') + : new Node\Expr\Array_(); + $stmts = []; foreach ($byRefParamNames as $pName) { $checkCall = new Node\Expr\FuncCall( @@ -563,6 +570,7 @@ public static function buildParamOutCheckStmts(array $byRefParamNames, Node\Expr new Node\Arg(new Node\Scalar\String_($pName)), new Node\Arg(new Node\Expr\Variable($pName)), new Node\Arg($thisArg), + new Node\Arg($varsArg), ] ); @@ -798,8 +806,13 @@ public static function buildParamOutGuardExpr( array $byRefParamNames, Node\Expr $innerExpr, Node\Expr $thisArg, - ?int $line = null + ?int $line = null, + bool $needsReturnVars = false ): Node\Expr { + $varsArg = $needsReturnVars + ? new Node\Expr\Variable('_typephpArgs') + : new Node\Expr\Array_(); + $expr = $innerExpr; foreach (array_reverse($byRefParamNames) as $pName) { $checkCall = new Node\Expr\FuncCall( @@ -809,6 +822,7 @@ public static function buildParamOutGuardExpr( new Node\Arg(new Node\Scalar\String_($pName)), new Node\Arg(new Node\Expr\Variable($pName)), new Node\Arg($thisArg), + new Node\Arg($varsArg), ] ); @@ -833,7 +847,8 @@ public static function buildWrappedYieldNode( Node\Expr $thisArg, bool $wrapYield = true, bool $wrapSend = true, - array $byRefParams = [] + array $byRefParams = [], + bool $needsReturnVars = false ): Node\Expr { if ($wrapYield) { $checkYieldCall = new Node\Expr\FuncCall( @@ -858,7 +873,7 @@ public static function buildWrappedYieldNode( if ($byRefParams !== []) { $valExpr = $n->value ?? new Node\Expr\ConstFetch(new Node\Name('null')); - $n->value = self::buildParamOutGuardExpr($byRefParams, $valExpr, $thisArg, $n->getStartLine()); + $n->value = self::buildParamOutGuardExpr($byRefParams, $valExpr, $thisArg, $n->getStartLine(), $needsReturnVars); } if (! $wrapSend) { @@ -917,7 +932,7 @@ private static function wrapGeneratorReturns( } $traverser = new NodeTraverser(); - $traverser->addVisitor(new class ( + $traverser->addVisitor(new class( $thisArg, $genContract, $currentFile, @@ -936,8 +951,7 @@ public function __construct( private bool $needsReturnVars, private array $byRefParams, private bool $hasSelfOut - ) { - } + ) {} public function enterNode(Node $n): int|Node|array|null { @@ -991,7 +1005,14 @@ public function enterNode(Node $n): int|Node|array|null return null; } - return FunctionContractInjector::buildWrappedYieldNode($n, $this->thisArg, $wrapYield, $wrapSend, $this->byRefParams); + return FunctionContractInjector::buildWrappedYieldNode( + $n, + $this->thisArg, + $wrapYield, + $wrapSend, + $this->byRefParams, + $this->needsReturnVars + ); } if ($n instanceof Node\Expr\YieldFrom) { @@ -1025,7 +1046,8 @@ public function enterNode(Node $n): int|Node|array|null $this->byRefParams, $n->expr, $this->thisArg, - $n->getStartLine() + $n->getStartLine(), + $this->needsReturnVars ); } @@ -1044,7 +1066,7 @@ public function enterNode(Node $n): int|Node|array|null } $paramOutStmts = $this->byRefParams !== [] - ? FunctionContractInjector::buildParamOutCheckStmts($this->byRefParams, $this->thisArg) + ? FunctionContractInjector::buildParamOutCheckStmts($this->byRefParams, $this->thisArg, $this->needsReturnVars) : []; if ($paramOutStmts !== []) { @@ -1095,7 +1117,7 @@ public function enterNode(Node $n): int|Node|array|null } $paramOutStmts = $byRefParams !== [] - ? self::buildParamOutCheckStmts($byRefParams, $thisArg) + ? self::buildParamOutCheckStmts($byRefParams, $thisArg, $needsReturnVars) : []; if ($paramOutStmts !== []) { @@ -1156,7 +1178,7 @@ private static function wrapNonGeneratorReturns( self::tagPrecedingAssignments($stmts); $traverser = new NodeTraverser(); - $traverser->addVisitor(new class ( + $traverser->addVisitor(new class( $thisArg, $isNativeVoid, $needsReturnVars, @@ -1185,8 +1207,7 @@ public function __construct( private ?array $classContext, private ?TypeNode $returnTypeNode, private string $currentFile - ) { - } + ) {} public function enterNode(Node $n): int|array|null { @@ -1224,7 +1245,7 @@ public function enterNode(Node $n): int|array|null } $paramOutStmts = $this->byRefParams !== [] - ? FunctionContractInjector::buildParamOutCheckStmts($this->byRefParams, $this->thisArg) + ? FunctionContractInjector::buildParamOutCheckStmts($this->byRefParams, $this->thisArg, $this->needsReturnVars) : []; if ($paramOutStmts !== []) { @@ -1286,7 +1307,7 @@ public function enterNode(Node $n): int|array|null } $paramOutStmts = $byRefParams !== [] - ? self::buildParamOutCheckStmts($byRefParams, $thisArg) + ? self::buildParamOutCheckStmts($byRefParams, $thisArg, $needsReturnVars) : []; if ($paramOutStmts !== []) { diff --git a/src/Internal/Checker/ParamOutChecker.php b/src/Internal/Checker/ParamOutChecker.php index 040e17e2..45db2f4d 100644 --- a/src/Internal/Checker/ParamOutChecker.php +++ b/src/Internal/Checker/ParamOutChecker.php @@ -29,13 +29,17 @@ public static function reset(): void self::$noParamOutContractCache = []; } + /** + * @param array $vars + */ public static function checkParamOut( string $function, string $paramName, mixed $value, object|string|null $thisOrClass, TypeValidatorRegistry $registry, - string $effectiveFunction = '' + string $effectiveFunction = '', + array $vars = [] ): ?ErrorMessage { if (! Config::isParamsEnabled()) { return null; @@ -66,7 +70,7 @@ public static function checkParamOut( return null; } - $paramOuts = $contract['paramOuts'] ?? []; + $paramOuts = $paramOuts = $contract['paramOuts'] ?? []; if (! isset($paramOuts[$paramName])) { return null; @@ -79,7 +83,7 @@ public static function checkParamOut( : []; if (ConditionalChecker::containsConditional($typeNode)) { - $typeNode = ConditionalChecker::resolve($typeNode, [], $boundTemplates, $registry, $effectiveFunction); + $typeNode = ConditionalChecker::resolve($typeNode, $vars, $boundTemplates, $registry, $effectiveFunction); } if (\count($boundTemplates) > 0 || \count($allTemplates) > 0) { @@ -88,7 +92,7 @@ public static function checkParamOut( $typeNode = SpecialTypeResolver::resolve($typeNode, $effectiveFunction, $thisObj); if (ConditionalChecker::containsConditional($typeNode)) { - $typeNode = ConditionalChecker::resolve($typeNode, [], $boundTemplates, $registry, $effectiveFunction); + $typeNode = ConditionalChecker::resolve($typeNode, $vars, $boundTemplates, $registry, $effectiveFunction); } $context = $effectiveFunction . '(): Argument &$' . $paramName . ' (param-out)'; diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index 1792d925..b0dc9c71 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -410,9 +410,16 @@ public static function checkParams(string $function, array $vars, object|string| /** * Validates a by-reference parameter's post-condition (@param-out) upon exit. + * + * @param array|null $vars */ - public static function checkParamOut(string $function, string $paramName, mixed $value, object|string|null $thisOrClass = null): ?ErrorMessage - { + public static function checkParamOut( + string $function, + string $paramName, + mixed $value, + object|string|null $thisOrClass = null, + ?array $vars = [] + ): ?ErrorMessage { if (! Config::isEnabled() || ! Config::isParamsOutEnabled()) { return null; } @@ -424,7 +431,9 @@ public static function checkParamOut(string $function, string $paramName, mixed return null; } - $res = ParamOutChecker::checkParamOut($function, $paramName, $value, $thisOrClass, self::getRegistry(), $effectiveFunction); + $vars = $vars !== null ? $vars : []; + + $res = ParamOutChecker::checkParamOut($function, $paramName, $value, $thisOrClass, self::getRegistry(), $effectiveFunction, $vars); if ($res instanceof ErrorMessage) { if (IgnoreManager::isCallerIgnored()) { diff --git a/tests/TypeChecking/Boundaries/ParamOutContractsTest.php b/tests/TypeChecking/Boundaries/ParamOutContractsTest.php index 2dcc478b..e24fb986 100644 --- a/tests/TypeChecking/Boundaries/ParamOutContractsTest.php +++ b/tests/TypeChecking/Boundaries/ParamOutContractsTest.php @@ -357,6 +357,47 @@ public function runValid(mixed &$x): Generator } } +/** + * 13. Parameter-based conditional @param-out on standalone function + * + * @param bool $asInt + * @param mixed &$out + * + * @param-out ($asInt is true ? positive-int : non-empty-string) $out + */ +function tddParamOutConditionalByFlag(bool $asInt, mixed &$out, mixed $newVal): void +{ + $out = $newVal; +} + +class IssueParamOutConditionalService +{ + /** + * @param 'int'|'string' $format + * @param mixed &$out + * + * @param-out ($format is 'int' ? positive-int : non-empty-string) $out + */ + public function formatOutput(string $format, mixed &$out, mixed $newVal): void + { + $out = $newVal; + } + + /** + * Mutates $asInt inside the body before exit (must evaluate against initial entry argument!) + * + * @param bool $asInt + * @param mixed &$out + * + * @param-out ($asInt is true ? positive-int : non-empty-string) $out + */ + public function mutateFlagBeforeExit(bool $asInt, mixed &$out, mixed $newVal): void + { + $asInt = false; + $out = $newVal; + } +} + describe('@param-out & @phpstan-param-out Contracts', function () { describe('1. Basic Scalar @param-out', function () { test('accepts valid post-condition mutation on by-ref parameter', function () { @@ -369,9 +410,8 @@ public function runValid(mixed &$x): Generator test('throws TypeError when function mutates by-ref parameter to invalid value', function () { $val = 'initial_string'; - expect(fn () => tddParamOutBasic($val, makeInvalid: true)) - ->toThrow(TypeError::class, 'Argument &$value (param-out) must be of type positive-int, negative int (-50) given') - ; + expect(fn() => tddParamOutBasic($val, makeInvalid: true)) + ->toThrow(TypeError::class, 'Argument &$value (param-out) must be of type positive-int, negative int (-50) given'); }); }); @@ -382,25 +422,22 @@ public function runValid(mixed &$x): Generator tddPsalmParamOutStandalone($token, makeInvalid: false); expect($token)->toBe('tok_valid_123'); - expect(fn () => tddPsalmParamOutStandalone($token, makeInvalid: true)) - ->toThrow(TypeError::class, 'Argument &$token (param-out) must be of type non-empty-string') - ; + expect(fn() => tddPsalmParamOutStandalone($token, makeInvalid: true)) + ->toThrow(TypeError::class, 'Argument &$token (param-out) must be of type non-empty-string'); }); test('prioritizes @psalm-param-out over @param-out when @phpstan-param-out is absent', function () { $code = 'init'; - expect(fn () => tddPsalmOverridesStandardParamOut($code)) - ->toThrow(TypeError::class, 'Argument &$code (param-out) must be of type non-empty-string') - ; + expect(fn() => tddPsalmOverridesStandardParamOut($code)) + ->toThrow(TypeError::class, 'Argument &$code (param-out) must be of type non-empty-string'); }); test('prioritizes @phpstan-param-out over both @psalm-param-out and @param-out', function () { $id = 0; - expect(fn () => tddTriplePriorityParamOut($id)) - ->toThrow(TypeError::class, 'Argument &$id (param-out) must be of type positive-int, negative int (-5) given') - ; + expect(fn() => tddTriplePriorityParamOut($id)) + ->toThrow(TypeError::class, 'Argument &$id (param-out) must be of type positive-int, negative int (-5) given'); }); }); @@ -413,9 +450,8 @@ public function runValid(mixed &$x): Generator ->and($status)->toBe('active') ; - expect(fn () => tddParamOutWithReturn($status, makeInvalid: true)) - ->toThrow(TypeError::class, "Argument &\$status (param-out) must be of type ('active' | 'pending')") - ; + expect(fn() => tddParamOutWithReturn($status, makeInvalid: true)) + ->toThrow(TypeError::class, "Argument &\$status (param-out) must be of type ('active' | 'pending')"); }); }); @@ -430,9 +466,8 @@ public function runValid(mixed &$x): Generator ]); $badPayload = []; - expect(fn () => tddParamOutArrayShape($badPayload, makeInvalid: true)) - ->toThrow(TypeError::class, "Argument &\$payload (param-out)['id'] must be of type positive-int") - ; + expect(fn() => tddParamOutArrayShape($badPayload, makeInvalid: true)) + ->toThrow(TypeError::class, "Argument &\$payload (param-out)['id'] must be of type positive-int"); }); }); @@ -444,13 +479,11 @@ public function runValid(mixed &$x): Generator tddMultipleParamOut($id, $name, invalidId: false, invalidName: false); expect($id)->toBe(100)->and($name)->toBe('Alice'); - expect(fn () => tddMultipleParamOut($id, $name, invalidId: true, invalidName: false)) - ->toThrow(TypeError::class, 'Argument &$id (param-out) must be of type positive-int') - ; + expect(fn() => tddMultipleParamOut($id, $name, invalidId: true, invalidName: false)) + ->toThrow(TypeError::class, 'Argument &$id (param-out) must be of type positive-int'); - expect(fn () => tddMultipleParamOut($id, $name, invalidId: false, invalidName: true)) - ->toThrow(TypeError::class, 'Argument &$name (param-out) must be of type non-empty-string') - ; + expect(fn() => tddMultipleParamOut($id, $name, invalidId: false, invalidName: true)) + ->toThrow(TypeError::class, 'Argument &$name (param-out) must be of type non-empty-string'); }); }); @@ -462,9 +495,8 @@ public function runValid(mixed &$x): Generator tddGenericParamOut($dog, $result, passCar: false); expect($result)->toBe($dog); - expect(fn () => tddGenericParamOut($dog, $result, passCar: true)) - ->toThrow(TypeError::class, Dog::class) - ; + expect(fn() => tddGenericParamOut($dog, $result, passCar: true)) + ->toThrow(TypeError::class, Dog::class); }); }); @@ -476,9 +508,8 @@ public function runValid(mixed &$x): Generator $service->mutate($num, invalid: false); expect($num)->toBe(999); - expect(fn () => $service->mutate($num, invalid: true)) - ->toThrow(TypeError::class, 'Argument &$data (param-out) must be of type positive-int') - ; + expect(fn() => $service->mutate($num, invalid: true)) + ->toThrow(TypeError::class, 'Argument &$data (param-out) must be of type positive-int'); }); }); @@ -495,13 +526,11 @@ public function runValid(mixed &$x): Generator test('rejects values violating all union members in @param-out', function () { $val = null; - expect(fn () => tddParamOutUnion($val, -5)) - ->toThrow(TypeError::class, 'Argument &$val (param-out) must be of type (positive-int | non-empty-string)') - ; + expect(fn() => tddParamOutUnion($val, -5)) + ->toThrow(TypeError::class, 'Argument &$val (param-out) must be of type (positive-int | non-empty-string)'); - expect(fn () => tddParamOutUnion($val, '')) - ->toThrow(TypeError::class, 'Argument &$val (param-out) must be of type (positive-int | non-empty-string)') - ; + expect(fn() => tddParamOutUnion($val, '')) + ->toThrow(TypeError::class, 'Argument &$val (param-out) must be of type (positive-int | non-empty-string)'); }); test('diagnoses exact failing branch in discriminated union shape @param-out', function () { @@ -513,13 +542,11 @@ public function runValid(mixed &$x): Generator tddParamOutDiscriminatedUnion($payload, ['type' => 'B', 'code' => 'TOKEN']); expect($payload)->toBe(['type' => 'B', 'code' => 'TOKEN']); - expect(fn () => tddParamOutDiscriminatedUnion($payload, ['type' => 'A', 'id' => -10])) - ->toThrow(TypeError::class, "Argument &\$payload (param-out)['id'] must be of type positive-int") - ; + expect(fn() => tddParamOutDiscriminatedUnion($payload, ['type' => 'A', 'id' => -10])) + ->toThrow(TypeError::class, "Argument &\$payload (param-out)['id'] must be of type positive-int"); - expect(fn () => tddParamOutDiscriminatedUnion($payload, ['type' => 'B', 'code' => ''])) - ->toThrow(TypeError::class, "Argument &\$payload (param-out)['code'] must be of type non-empty-string") - ; + expect(fn() => tddParamOutDiscriminatedUnion($payload, ['type' => 'B', 'code' => ''])) + ->toThrow(TypeError::class, "Argument &\$payload (param-out)['code'] must be of type non-empty-string"); }); }); @@ -536,9 +563,8 @@ public function runValid(mixed &$x): Generator $collection = null; $onlyCountable = new CountableOnly(); - expect(fn () => tddParamOutIntersection($collection, $onlyCountable)) - ->toThrow(TypeError::class, 'Argument &$collection (param-out) must be of type (Countable & ArrayAccess)') - ; + expect(fn() => tddParamOutIntersection($collection, $onlyCountable)) + ->toThrow(TypeError::class, 'Argument &$collection (param-out) must be of type (Countable & ArrayAccess)'); }); test('merges and validates composed array shapes in @param-out (ShapeA & ShapeB)', function () { @@ -547,16 +573,13 @@ public function runValid(mixed &$x): Generator tddParamOutShapeComposition($data, ['id' => 10, 'name' => 'Alice']); expect($data)->toBe(['id' => 10, 'name' => 'Alice']); - expect(fn () => tddParamOutShapeComposition($data, ['id' => -1, 'name' => 'Alice'])) - ->toThrow(TypeError::class, "Argument &\$data (param-out)['id'] must be of type positive-int") - ; - expect(fn () => tddParamOutShapeComposition($data, ['id' => 10, 'name' => ''])) - ->toThrow(TypeError::class, "Argument &\$data (param-out)['name'] must be of type non-empty-string") - ; + expect(fn() => tddParamOutShapeComposition($data, ['id' => -1, 'name' => 'Alice'])) + ->toThrow(TypeError::class, "Argument &\$data (param-out)['id'] must be of type positive-int"); + expect(fn() => tddParamOutShapeComposition($data, ['id' => 10, 'name' => ''])) + ->toThrow(TypeError::class, "Argument &\$data (param-out)['name'] must be of type non-empty-string"); - expect(fn () => tddParamOutShapeComposition($data, ['id' => 10, 'name' => 'Alice', 'extra' => true])) - ->toThrow(TypeError::class, "Argument &\$data (param-out) contains unsealed unexpected key 'extra'") - ; + expect(fn() => tddParamOutShapeComposition($data, ['id' => 10, 'name' => 'Alice', 'extra' => true])) + ->toThrow(TypeError::class, "Argument &\$data (param-out) contains unsealed unexpected key 'extra'"); }); }); @@ -565,45 +588,40 @@ public function runValid(mixed &$x): Generator $a = new Issue1SingleLineParamOutA(); $v = 1; - expect(fn () => $a->run($v)) - ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int') - ; + expect(fn() => $a->run($v)) + ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int'); }); test('Class B: single-line @param and @param-out with &$x ampersand throws TypeError', function () { $b = new Issue1SingleLineAmpersandB(); $v = 1; - expect(fn () => $b->run($v)) - ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int') - ; + expect(fn() => $b->run($v)) + ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int'); }); test('Class C: single-line @param, @param-out, and @return throws TypeError', function () { $c = new Issue1SingleLineWithReturnC(); $v = 1; - expect(fn () => $c->run($v)) - ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int') - ; + expect(fn() => $c->run($v)) + ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int'); }); test('Class D: single-line @param and @phpstan-param-out throws TypeError', function () { $d = new Issue1SingleLinePhpstanD(); $v = 1; - expect(fn () => $d->run($v)) - ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int') - ; + expect(fn() => $d->run($v)) + ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int'); }); test('Class E: multi-line @param-out with &$x ampersand throws TypeError', function () { $e = new Issue1MultiLineAmpersandE(); $v = 1; - expect(fn () => $e->run($v)) - ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int') - ; + expect(fn() => $e->run($v)) + ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int'); }); }); @@ -612,17 +630,15 @@ public function runValid(mixed &$x): Generator $service = new Issue2GenericMethodWithParamOut(); $v = 42; - expect(fn () => $service->run($v)) - ->toThrow(TypeError::class, 'Return value must be of type int') - ; + expect(fn() => $service->run($v)) + ->toThrow(TypeError::class, 'Return value must be of type int'); }); test('enforces generic @return T after @param-out check passes on standalone function', function () { $v = 42; - expect(fn () => issue2StandaloneGenericWithParamOut($v)) - ->toThrow(TypeError::class, 'Return value must be of type int') - ; + expect(fn() => issue2StandaloneGenericWithParamOut($v)) + ->toThrow(TypeError::class, 'Return value must be of type int'); }); test('preserves generic template T across multiple sequential @param-out checks in the same method', function () { @@ -630,9 +646,8 @@ public function runValid(mixed &$x): Generator $first = 42; $second = 100; - expect(fn () => $service->syncBoth($first, $second)) - ->toThrow(TypeError::class, 'Argument &$second (param-out) must be of type int') - ; + expect(fn() => $service->syncBoth($first, $second)) + ->toThrow(TypeError::class, 'Argument &$second (param-out) must be of type int'); }); }); @@ -653,9 +668,8 @@ public function runValid(mixed &$x): Generator $gen = $service->runInvalidBeforeYield($x); - expect(fn () => $gen->current()) - ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int') - ; + expect(fn() => $gen->current()) + ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int'); }); test('throws TypeError when generator mutates by-ref param to invalid type after yield before finishing', function () { @@ -679,4 +693,47 @@ public function runValid(mixed &$x): Generator ; }); }); + + describe('13. Parameter-Based Conditional @param-out ($param is Target ? A : B)', function () { + test('evaluates true branch (positive-int) on standalone function when $asInt is true', function () { + $out = null; + tddParamOutConditionalByFlag(true, $out, 42); + expect($out)->toBe(42); + + expect(fn() => tddParamOutConditionalByFlag(true, $out, -10)) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type positive-int'); + }); + + test('evaluates else branch (non-empty-string) on standalone function when $asInt is false', function () { + $out = null; + tddParamOutConditionalByFlag(false, $out, 'valid_text'); + expect($out)->toBe('valid_text'); + + expect(fn() => tddParamOutConditionalByFlag(false, $out, '')) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type non-empty-string'); + }); + + test('evaluates parameter-based conditional @param-out on class methods and preserves entry argument on in-body mutation', function () { + $service = new IssueParamOutConditionalService(); + $out = null; + + $service->formatOutput('int', $out, 100); + expect($out)->toBe(100); + + expect(fn() => $service->formatOutput('int', $out, -5)) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type positive-int'); + + $service->formatOutput('string', $out, 'hello'); + expect($out)->toBe('hello'); + + expect(fn() => $service->formatOutput('string', $out, '')) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type non-empty-string'); + + $service->mutateFlagBeforeExit(true, $out, 50); + expect($out)->toBe(50); + + expect(fn() => $service->mutateFlagBeforeExit(true, $out, 'wrong_branch')) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type positive-int'); + }); + }); }); From 8b833ca718df3e91b51784825742527f53606186 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Fri, 6 Nov 2026 18:32:38 +0800 Subject: [PATCH 05/11] Enhance conditional type handling in GeneratorChecker and IterableWrapper with new checks and tests for conditional generators and iterables --- src/Internal/Checker/GeneratorChecker.php | 28 +++-- src/Internal/Wrapper/IterableWrapper.php | 14 +++ .../GenericIteratorsAndGeneratorsTest.php | 104 +++++++++++++++++- 3 files changed, 132 insertions(+), 14 deletions(-) diff --git a/src/Internal/Checker/GeneratorChecker.php b/src/Internal/Checker/GeneratorChecker.php index 33e1b6c2..c4a102b5 100644 --- a/src/Internal/Checker/GeneratorChecker.php +++ b/src/Internal/Checker/GeneratorChecker.php @@ -57,7 +57,7 @@ public static function checkSend( return null; } - $types = self::resolveYieldAndSendTypes($function, $thisOrClass); + $types = self::resolveYieldAndSendTypes($function, $thisOrClass, $registry); if ($types === null) { return $sendValue; } @@ -82,7 +82,7 @@ public static function checkYield( TypeValidatorRegistry $registry, object|string|null $thisOrClass = null ): mixed { - $types = self::resolveYieldAndSendTypes($function, $thisOrClass); + $types = self::resolveYieldAndSendTypes($function, $thisOrClass, $registry); if ($types === null) { return $value; } @@ -115,7 +115,7 @@ public static function checkReturn( TypeValidatorRegistry $registry, object|string|null $thisOrClass = null ): mixed { - $types = self::resolveYieldAndSendTypes($function, $thisOrClass); + $types = self::resolveYieldAndSendTypes($function, $thisOrClass, $registry); if ($types === null) { return $value; } @@ -143,8 +143,11 @@ public static function checkReturn( * * @return array{0: ?TypeNode, 1: ?TypeNode, 2: ?TypeNode, 3: ?TypeNode}|null */ - private static function resolveYieldAndSendTypes(string $function, object|string|null $thisOrClass): ?array - { + private static function resolveYieldAndSendTypes( + string $function, + object|string|null $thisOrClass, + ?TypeValidatorRegistry $registry = null + ): ?array { if (isset(self::$noContractCache[$function])) { return null; } @@ -166,10 +169,11 @@ private static function resolveYieldAndSendTypes(string $function, object|string $aliases = $contract['aliases'] ?? []; $hasGenerics = \count($allTemplates) > 0; $hasAliases = \count($aliases) > 0; + $hasConditionals = ConditionalChecker::containsConditional($returnTypeNode); $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; // Static / non-generic generator: cache permanently for this function - if (! $hasGenerics && ! $hasAliases && $thisObj === null) { + if (! $hasGenerics && ! $hasAliases && ! $hasConditionals && $thisObj === null) { $resolvedNode = SpecialTypeResolver::resolve($returnTypeNode, $function, null); return self::$staticYieldTypeCache[$function] = self::extractYieldTypes($resolvedNode); @@ -180,7 +184,7 @@ private static function resolveYieldAndSendTypes(string $function, object|string $sig = null; $boundCount = \count($boundTemplates); - if ($boundCount > 0 && $boundCount <= 2 && ! $hasAliases && $thisObj === null) { + if ($boundCount > 0 && $boundCount <= 2 && ! $hasAliases && ! $hasConditionals && $thisObj === null) { if ($boundCount === 1) { $first = reset($boundTemplates); $sig = $first instanceof IdentifierTypeNode ? $first->name : (string) $first; @@ -200,11 +204,19 @@ private static function resolveYieldAndSendTypes(string $function, object|string $returnTypeNode = $aliases[$returnTypeNode->name]; } + if ($hasConditionals && $registry !== null) { + $returnTypeNode = ConditionalChecker::resolve($returnTypeNode, [], $boundTemplates, $registry, $function); + } + if (\count($boundTemplates) > 0 || \count($allTemplates) > 0) { $returnTypeNode = TemplateSubstitutor::substitute($returnTypeNode, $boundTemplates, $allTemplates); $returnTypeNode = SpecialTypeResolver::resolve($returnTypeNode, $function, $thisObj); } + if (ConditionalChecker::containsConditional($returnTypeNode) && $registry !== null) { + $returnTypeNode = ConditionalChecker::resolve($returnTypeNode, [], $boundTemplates, $registry, $function); + } + $types = self::extractYieldTypes($returnTypeNode); if ($sig !== null) { @@ -249,4 +261,4 @@ private static function extractYieldTypes(TypeNode $returnTypeNode): array return [$keyTypeNode, $itemTypeNode, $sendTypeNode, $generatorReturnTypeNode]; } -} +} \ No newline at end of file diff --git a/src/Internal/Wrapper/IterableWrapper.php b/src/Internal/Wrapper/IterableWrapper.php index bd8fedc4..2067c001 100644 --- a/src/Internal/Wrapper/IterableWrapper.php +++ b/src/Internal/Wrapper/IterableWrapper.php @@ -19,6 +19,7 @@ use TypePHP\Internal\Resolver\CallerBoundaryResolver; use TypePHP\Internal\Resolver\SpecialTypeResolver; use TypePHP\Internal\Validator\TypeValidatorRegistry; +use TypePHP\Internal\Checker\ConditionalChecker; /** * Wraps Traversable objects and Generators to evaluate key and value type constraints lazily during iteration. @@ -53,6 +54,19 @@ public static function wrap(string $function, string $paramName, mixed $iterable $thisObj = \is_object($thisOrClass) ? $thisOrClass : null; $boundTemplates = TemplateManager::getBoundTemplates($function, $thisObj, $templates); + if (ConditionalChecker::containsConditional($typeNode)) { + $typeNode = ConditionalChecker::resolve($typeNode, [], $boundTemplates, $registry, $function); + } + + if (\count($boundTemplates) > 0 || \count($templates) > 0) { + $typeNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $templates); + $typeNode = SpecialTypeResolver::resolve($typeNode, $function, $thisObj); + } + + if (ConditionalChecker::containsConditional($typeNode)) { + $typeNode = ConditionalChecker::resolve($typeNode, [], $boundTemplates, $registry, $function); + } + if (\count($boundTemplates) > 0 || \count($templates) > 0) { $typeNode = TemplateSubstitutor::substitute($typeNode, $boundTemplates, $templates); $typeNode = SpecialTypeResolver::resolve($typeNode, $function, $thisObj); diff --git a/tests/TypeChecking/CallablesAndIterators/GenericIteratorsAndGeneratorsTest.php b/tests/TypeChecking/CallablesAndIterators/GenericIteratorsAndGeneratorsTest.php index d3cdc053..9189cf59 100644 --- a/tests/TypeChecking/CallablesAndIterators/GenericIteratorsAndGeneratorsTest.php +++ b/tests/TypeChecking/CallablesAndIterators/GenericIteratorsAndGeneratorsTest.php @@ -63,6 +63,56 @@ public function run(): Generator } } +/** + * Top-level conditional generator return with default template T = int + * + * @template T = int + * + * @param T|null $sample + * @param mixed $yieldValue + * + * @return (T is int ? Generator : Generator) + */ +function testConditionalGeneratorReturn(mixed $sample = null, mixed $yieldValue = null): Generator +{ + yield 0 => $yieldValue; +} + +/** + * Nested conditional element inside Generator return + * + * @template T = int + * + * @param T|null $sample + * @param mixed $yieldValue + * + * @return Generator + */ +function testNestedConditionalGeneratorReturn(mixed $sample = null, mixed $yieldValue = null): Generator +{ + yield 0 => $yieldValue; +} + +/** + * Conditional iterable parameter with Traversable lazy wrapping + * + * @template T = int + * + * @param iterable $stream + * @param T|null $sample + * + * @return list + */ +function testConditionalIterableParam(iterable $stream, mixed $sample = null): array +{ + $collected = []; + foreach ($stream as $item) { + $collected[] = $item; + } + + return $collected; +} + describe('Generic Iterables & Generators (@template T with iterable and Generator)', function () { describe('Generic Iterable Parameters (iterable)', function () { test('collects items from iterable matching inferred template T = int', function () { @@ -158,18 +208,16 @@ public function run(): Generator $gen->current(); - expect(fn () => $gen->send('invalid')) - ->toThrow(TypeError::class, 'must be of type int') - ; + expect(fn() => $gen->send('invalid')) + ->toThrow(TypeError::class, 'must be of type int'); }); test('strictly enforces TSend = void and throws TypeError when non-null value is sent into generator', function () { $g = (new D2GeneratorFixture())->run(); $g->current(); - expect(fn () => $g->send('not null')) - ->toThrow(TypeError::class, 'Generator sent value (TSend) must be of type void, string \'not null\' given') - ; + expect(fn() => $g->send('not null')) + ->toThrow(TypeError::class, 'Generator sent value (TSend) must be of type void, string \'not null\' given'); }); test('allows standard foreach iteration on generator with TSend = void', function () { @@ -211,4 +259,48 @@ public function run(): Generator })->toThrow(TypeError::class, 'must be of type void'); }); }); + + describe('Conditional Generator & Iterable Contracts', function () { + test('validates top-level conditional generator return with default T = int and overridden T = string', function () { + $validIntGen = testConditionalGeneratorReturn(null, 42); + expect(iterator_to_array($validIntGen))->toBe([0 => 42]); + + $badIntGen = testConditionalGeneratorReturn(null, -10); + expect(fn() => iterator_to_array($badIntGen)) + ->toThrow(TypeError::class, 'Return iterator value must be of type positive-int'); + + $validStrGen = testConditionalGeneratorReturn('override', 'hello'); + expect(iterator_to_array($validStrGen))->toBe([0 => 'hello']); + + $badStrGen = testConditionalGeneratorReturn('override', ''); + expect(fn() => iterator_to_array($badStrGen)) + ->toThrow(TypeError::class, 'Return iterator value must be of type non-empty-string'); + }); + + test('validates nested conditional element inside Generator', function () { + $validGen = testNestedConditionalGeneratorReturn(null, 100); + expect(iterator_to_array($validGen))->toBe([0 => 100]); + + $badGen = testNestedConditionalGeneratorReturn(null, -5); + expect(fn() => iterator_to_array($badGen)) + ->toThrow(TypeError::class, 'Return iterator value must be of type positive-int'); + + $badStrGen = testNestedConditionalGeneratorReturn('override', ''); + expect(fn() => iterator_to_array($badStrGen)) + ->toThrow(TypeError::class, 'Return iterator value must be of type non-empty-string'); + }); + + test('lazily validates conditional iterable parameter on Traversable iteration', function () { + $validIter = new ArrayIterator([10, 20, 30]); + expect(testConditionalIterableParam($validIter))->toBe([10, 20, 30]); + + $badIntIter = new ArrayIterator([10, -5, 30]); + expect(fn() => testConditionalIterableParam($badIntIter)) + ->toThrow(TypeError::class, 'Iterator $stream value must be of type positive-int'); + + $badStrIter = new ArrayIterator(['valid', '']); + expect(fn() => testConditionalIterableParam($badStrIter, 'override')) + ->toThrow(TypeError::class, 'Iterator $stream value must be of type non-empty-string'); + }); + }); }); From c3d5bfb15a8ae00d22122763555f1d542cd9cc2f Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Fri, 6 Nov 2026 18:50:35 +0800 Subject: [PATCH 06/11] Enhance code formatting and add new static methods for default template handling in TemplateManager and DefaultTemplateTypesTest --- src/Internal/Ast/FunctionContractInjector.php | 12 +- src/Internal/Checker/GeneratorChecker.php | 2 +- src/Internal/Generics/TemplateManager.php | 54 +++++- src/Internal/Io/CacheManager.php | 2 +- src/Internal/Wrapper/IterableWrapper.php | 2 +- .../Boundaries/ParamOutContractsTest.php | 157 +++++++++++------- .../GenericIteratorsAndGeneratorsTest.php | 37 +++-- .../Generics/DefaultTemplateTypesTest.php | 97 ++++++++++- .../Generics/FBoundedPolymorphismTest.php | 2 +- 9 files changed, 269 insertions(+), 96 deletions(-) diff --git a/src/Internal/Ast/FunctionContractInjector.php b/src/Internal/Ast/FunctionContractInjector.php index b5d3587a..22f06ce9 100644 --- a/src/Internal/Ast/FunctionContractInjector.php +++ b/src/Internal/Ast/FunctionContractInjector.php @@ -406,7 +406,7 @@ private static function resolveThisArg(bool $isClassMethod, Node\Stmt\Function_| private static function isGenerator(Node\Stmt\Function_|Node\Stmt\ClassMethod $node): bool { - $visitor = new class() extends NodeVisitorAbstract { + $visitor = new class () extends NodeVisitorAbstract { public bool $isGen = false; public function enterNode(Node $n): ?int @@ -932,7 +932,7 @@ private static function wrapGeneratorReturns( } $traverser = new NodeTraverser(); - $traverser->addVisitor(new class( + $traverser->addVisitor(new class ( $thisArg, $genContract, $currentFile, @@ -951,7 +951,8 @@ public function __construct( private bool $needsReturnVars, private array $byRefParams, private bool $hasSelfOut - ) {} + ) { + } public function enterNode(Node $n): int|Node|array|null { @@ -1178,7 +1179,7 @@ private static function wrapNonGeneratorReturns( self::tagPrecedingAssignments($stmts); $traverser = new NodeTraverser(); - $traverser->addVisitor(new class( + $traverser->addVisitor(new class ( $thisArg, $isNativeVoid, $needsReturnVars, @@ -1207,7 +1208,8 @@ public function __construct( private ?array $classContext, private ?TypeNode $returnTypeNode, private string $currentFile - ) {} + ) { + } public function enterNode(Node $n): int|array|null { diff --git a/src/Internal/Checker/GeneratorChecker.php b/src/Internal/Checker/GeneratorChecker.php index c4a102b5..9f7dc6f0 100644 --- a/src/Internal/Checker/GeneratorChecker.php +++ b/src/Internal/Checker/GeneratorChecker.php @@ -261,4 +261,4 @@ private static function extractYieldTypes(TypeNode $returnTypeNode): array return [$keyTypeNode, $itemTypeNode, $sendTypeNode, $generatorReturnTypeNode]; } -} \ No newline at end of file +} diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index 9ab7b5c4..4d63a368 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -627,6 +627,33 @@ public static function isFBounded(TemplateTagValueNode $templateNode, string $co ); } + /** + * Retrieves static class-level bindings including declared template defaults. + * + * @param class-string $className + * + * @return array + */ + public static function getClassStaticBindings(string $className): array + { + $bindings = self::getClassInheritedBindings($className); + + try { + $ref = new \ReflectionClass($className); + [$hierarchyTemplates] = self::collectHierarchyTemplatesAndVariances($ref); + + foreach ($hierarchyTemplates as $tName => $templateTag) { + if (! isset($bindings[$tName]) && $templateTag->default !== null && ! self::isUnspecializedDefault($templateTag)) { + $bindings[$tName] = $templateTag->default; + } + } + } catch (\Throwable $e) { + // Silently ignore reflection errors + } + + return $bindings; + } + /** * Retrieves currently bound template types for a function call or object instance / static class. * @@ -642,9 +669,10 @@ public static function getBoundTemplates(string $function, object|string|null $t if ($thisObj !== null) { self::ensureInstanceInherited($thisObj); - if (isset(self::$instanceTemplateBindings[$thisObj])) { - $bindings = self::$instanceTemplateBindings[$thisObj]; - } + $isCtor = str_ends_with(strtolower($function), '::__construct'); + $bindings = $isCtor + ? (self::$instanceTemplateBindings[$thisObj] ?? []) + : self::getBoundTemplatesForInstance($thisObj); $methodTemplates = self::getMethodTemplates($function); if ($methodTemplates !== []) { @@ -658,7 +686,7 @@ public static function getBoundTemplates(string $function, object|string|null $t : (str_contains($function, '::') ? explode('::', $function, 2)[0] : ''); if ($className !== '' && (class_exists($className, false) || class_exists($className) || interface_exists($className) || trait_exists($className))) { - $classBindings = self::getClassInheritedBindings($className); + $classBindings = self::getClassStaticBindings($className); $bindings = $classBindings; $methodTemplates = self::getMethodTemplates($function); @@ -797,7 +825,12 @@ public static function isBound(string $function, object|string|null $thisOrClass return false; } - return isset(self::$instanceTemplateBindings[$thisObj][$templateName]); + $isCtor = str_ends_with(strtolower($function), '::__construct'); + $instanceBindings = $isCtor + ? (self::$instanceTemplateBindings[$thisObj] ?? []) + : self::getBoundTemplatesForInstance($thisObj); + + return isset($instanceBindings[$templateName]); } $className = \is_string($thisOrClass) && $thisOrClass !== '' @@ -809,7 +842,7 @@ public static function isBound(string $function, object|string|null $thisOrClass return false; } - $classBindings = self::getClassInheritedBindings($className); + $classBindings = self::getClassStaticBindings($className); return isset($classBindings[$templateName]); } @@ -836,7 +869,12 @@ public static function getBoundType(string $function, object|string|null $thisOr return null; } - return self::$instanceTemplateBindings[$thisObj][$templateName] ?? null; + $isCtor = str_ends_with(strtolower($function), '::__construct'); + $instanceBindings = $isCtor + ? (self::$instanceTemplateBindings[$thisObj] ?? []) + : self::getBoundTemplatesForInstance($thisObj); + + return $instanceBindings[$templateName] ?? null; } $className = \is_string($thisOrClass) && $thisOrClass !== '' @@ -848,7 +886,7 @@ public static function getBoundType(string $function, object|string|null $thisOr return null; } - $classBindings = self::getClassInheritedBindings($className); + $classBindings = self::getClassStaticBindings($className); return $classBindings[$templateName] ?? null; } diff --git a/src/Internal/Io/CacheManager.php b/src/Internal/Io/CacheManager.php index 5a699127..2ba0f72e 100644 --- a/src/Internal/Io/CacheManager.php +++ b/src/Internal/Io/CacheManager.php @@ -15,7 +15,7 @@ final class CacheManager /** * Cache version prefix string. Bump this whenever AST printer/transformation rules change. */ - public const VERSION_PREFIX = 'v0.12.1_'; + public const VERSION_PREFIX = 'v0.12.3_'; /** * Cached absolute cache directory path. diff --git a/src/Internal/Wrapper/IterableWrapper.php b/src/Internal/Wrapper/IterableWrapper.php index 2067c001..caa71742 100644 --- a/src/Internal/Wrapper/IterableWrapper.php +++ b/src/Internal/Wrapper/IterableWrapper.php @@ -10,6 +10,7 @@ use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; use TypePHP\Exception\TypeError as TypePHPTypeError; +use TypePHP\Internal\Checker\ConditionalChecker; use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\ErrorMessage; use TypePHP\Internal\Docblock\DocblockParser; @@ -19,7 +20,6 @@ use TypePHP\Internal\Resolver\CallerBoundaryResolver; use TypePHP\Internal\Resolver\SpecialTypeResolver; use TypePHP\Internal\Validator\TypeValidatorRegistry; -use TypePHP\Internal\Checker\ConditionalChecker; /** * Wraps Traversable objects and Generators to evaluate key and value type constraints lazily during iteration. diff --git a/tests/TypeChecking/Boundaries/ParamOutContractsTest.php b/tests/TypeChecking/Boundaries/ParamOutContractsTest.php index e24fb986..28e22187 100644 --- a/tests/TypeChecking/Boundaries/ParamOutContractsTest.php +++ b/tests/TypeChecking/Boundaries/ParamOutContractsTest.php @@ -410,8 +410,9 @@ public function mutateFlagBeforeExit(bool $asInt, mixed &$out, mixed $newVal): v test('throws TypeError when function mutates by-ref parameter to invalid value', function () { $val = 'initial_string'; - expect(fn() => tddParamOutBasic($val, makeInvalid: true)) - ->toThrow(TypeError::class, 'Argument &$value (param-out) must be of type positive-int, negative int (-50) given'); + expect(fn () => tddParamOutBasic($val, makeInvalid: true)) + ->toThrow(TypeError::class, 'Argument &$value (param-out) must be of type positive-int, negative int (-50) given') + ; }); }); @@ -422,22 +423,25 @@ public function mutateFlagBeforeExit(bool $asInt, mixed &$out, mixed $newVal): v tddPsalmParamOutStandalone($token, makeInvalid: false); expect($token)->toBe('tok_valid_123'); - expect(fn() => tddPsalmParamOutStandalone($token, makeInvalid: true)) - ->toThrow(TypeError::class, 'Argument &$token (param-out) must be of type non-empty-string'); + expect(fn () => tddPsalmParamOutStandalone($token, makeInvalid: true)) + ->toThrow(TypeError::class, 'Argument &$token (param-out) must be of type non-empty-string') + ; }); test('prioritizes @psalm-param-out over @param-out when @phpstan-param-out is absent', function () { $code = 'init'; - expect(fn() => tddPsalmOverridesStandardParamOut($code)) - ->toThrow(TypeError::class, 'Argument &$code (param-out) must be of type non-empty-string'); + expect(fn () => tddPsalmOverridesStandardParamOut($code)) + ->toThrow(TypeError::class, 'Argument &$code (param-out) must be of type non-empty-string') + ; }); test('prioritizes @phpstan-param-out over both @psalm-param-out and @param-out', function () { $id = 0; - expect(fn() => tddTriplePriorityParamOut($id)) - ->toThrow(TypeError::class, 'Argument &$id (param-out) must be of type positive-int, negative int (-5) given'); + expect(fn () => tddTriplePriorityParamOut($id)) + ->toThrow(TypeError::class, 'Argument &$id (param-out) must be of type positive-int, negative int (-5) given') + ; }); }); @@ -450,8 +454,9 @@ public function mutateFlagBeforeExit(bool $asInt, mixed &$out, mixed $newVal): v ->and($status)->toBe('active') ; - expect(fn() => tddParamOutWithReturn($status, makeInvalid: true)) - ->toThrow(TypeError::class, "Argument &\$status (param-out) must be of type ('active' | 'pending')"); + expect(fn () => tddParamOutWithReturn($status, makeInvalid: true)) + ->toThrow(TypeError::class, "Argument &\$status (param-out) must be of type ('active' | 'pending')") + ; }); }); @@ -466,8 +471,9 @@ public function mutateFlagBeforeExit(bool $asInt, mixed &$out, mixed $newVal): v ]); $badPayload = []; - expect(fn() => tddParamOutArrayShape($badPayload, makeInvalid: true)) - ->toThrow(TypeError::class, "Argument &\$payload (param-out)['id'] must be of type positive-int"); + expect(fn () => tddParamOutArrayShape($badPayload, makeInvalid: true)) + ->toThrow(TypeError::class, "Argument &\$payload (param-out)['id'] must be of type positive-int") + ; }); }); @@ -479,11 +485,13 @@ public function mutateFlagBeforeExit(bool $asInt, mixed &$out, mixed $newVal): v tddMultipleParamOut($id, $name, invalidId: false, invalidName: false); expect($id)->toBe(100)->and($name)->toBe('Alice'); - expect(fn() => tddMultipleParamOut($id, $name, invalidId: true, invalidName: false)) - ->toThrow(TypeError::class, 'Argument &$id (param-out) must be of type positive-int'); + expect(fn () => tddMultipleParamOut($id, $name, invalidId: true, invalidName: false)) + ->toThrow(TypeError::class, 'Argument &$id (param-out) must be of type positive-int') + ; - expect(fn() => tddMultipleParamOut($id, $name, invalidId: false, invalidName: true)) - ->toThrow(TypeError::class, 'Argument &$name (param-out) must be of type non-empty-string'); + expect(fn () => tddMultipleParamOut($id, $name, invalidId: false, invalidName: true)) + ->toThrow(TypeError::class, 'Argument &$name (param-out) must be of type non-empty-string') + ; }); }); @@ -495,8 +503,9 @@ public function mutateFlagBeforeExit(bool $asInt, mixed &$out, mixed $newVal): v tddGenericParamOut($dog, $result, passCar: false); expect($result)->toBe($dog); - expect(fn() => tddGenericParamOut($dog, $result, passCar: true)) - ->toThrow(TypeError::class, Dog::class); + expect(fn () => tddGenericParamOut($dog, $result, passCar: true)) + ->toThrow(TypeError::class, Dog::class) + ; }); }); @@ -508,8 +517,9 @@ public function mutateFlagBeforeExit(bool $asInt, mixed &$out, mixed $newVal): v $service->mutate($num, invalid: false); expect($num)->toBe(999); - expect(fn() => $service->mutate($num, invalid: true)) - ->toThrow(TypeError::class, 'Argument &$data (param-out) must be of type positive-int'); + expect(fn () => $service->mutate($num, invalid: true)) + ->toThrow(TypeError::class, 'Argument &$data (param-out) must be of type positive-int') + ; }); }); @@ -526,11 +536,13 @@ public function mutateFlagBeforeExit(bool $asInt, mixed &$out, mixed $newVal): v test('rejects values violating all union members in @param-out', function () { $val = null; - expect(fn() => tddParamOutUnion($val, -5)) - ->toThrow(TypeError::class, 'Argument &$val (param-out) must be of type (positive-int | non-empty-string)'); + expect(fn () => tddParamOutUnion($val, -5)) + ->toThrow(TypeError::class, 'Argument &$val (param-out) must be of type (positive-int | non-empty-string)') + ; - expect(fn() => tddParamOutUnion($val, '')) - ->toThrow(TypeError::class, 'Argument &$val (param-out) must be of type (positive-int | non-empty-string)'); + expect(fn () => tddParamOutUnion($val, '')) + ->toThrow(TypeError::class, 'Argument &$val (param-out) must be of type (positive-int | non-empty-string)') + ; }); test('diagnoses exact failing branch in discriminated union shape @param-out', function () { @@ -542,11 +554,13 @@ public function mutateFlagBeforeExit(bool $asInt, mixed &$out, mixed $newVal): v tddParamOutDiscriminatedUnion($payload, ['type' => 'B', 'code' => 'TOKEN']); expect($payload)->toBe(['type' => 'B', 'code' => 'TOKEN']); - expect(fn() => tddParamOutDiscriminatedUnion($payload, ['type' => 'A', 'id' => -10])) - ->toThrow(TypeError::class, "Argument &\$payload (param-out)['id'] must be of type positive-int"); + expect(fn () => tddParamOutDiscriminatedUnion($payload, ['type' => 'A', 'id' => -10])) + ->toThrow(TypeError::class, "Argument &\$payload (param-out)['id'] must be of type positive-int") + ; - expect(fn() => tddParamOutDiscriminatedUnion($payload, ['type' => 'B', 'code' => ''])) - ->toThrow(TypeError::class, "Argument &\$payload (param-out)['code'] must be of type non-empty-string"); + expect(fn () => tddParamOutDiscriminatedUnion($payload, ['type' => 'B', 'code' => ''])) + ->toThrow(TypeError::class, "Argument &\$payload (param-out)['code'] must be of type non-empty-string") + ; }); }); @@ -563,8 +577,9 @@ public function mutateFlagBeforeExit(bool $asInt, mixed &$out, mixed $newVal): v $collection = null; $onlyCountable = new CountableOnly(); - expect(fn() => tddParamOutIntersection($collection, $onlyCountable)) - ->toThrow(TypeError::class, 'Argument &$collection (param-out) must be of type (Countable & ArrayAccess)'); + expect(fn () => tddParamOutIntersection($collection, $onlyCountable)) + ->toThrow(TypeError::class, 'Argument &$collection (param-out) must be of type (Countable & ArrayAccess)') + ; }); test('merges and validates composed array shapes in @param-out (ShapeA & ShapeB)', function () { @@ -573,13 +588,16 @@ public function mutateFlagBeforeExit(bool $asInt, mixed &$out, mixed $newVal): v tddParamOutShapeComposition($data, ['id' => 10, 'name' => 'Alice']); expect($data)->toBe(['id' => 10, 'name' => 'Alice']); - expect(fn() => tddParamOutShapeComposition($data, ['id' => -1, 'name' => 'Alice'])) - ->toThrow(TypeError::class, "Argument &\$data (param-out)['id'] must be of type positive-int"); - expect(fn() => tddParamOutShapeComposition($data, ['id' => 10, 'name' => ''])) - ->toThrow(TypeError::class, "Argument &\$data (param-out)['name'] must be of type non-empty-string"); + expect(fn () => tddParamOutShapeComposition($data, ['id' => -1, 'name' => 'Alice'])) + ->toThrow(TypeError::class, "Argument &\$data (param-out)['id'] must be of type positive-int") + ; + expect(fn () => tddParamOutShapeComposition($data, ['id' => 10, 'name' => ''])) + ->toThrow(TypeError::class, "Argument &\$data (param-out)['name'] must be of type non-empty-string") + ; - expect(fn() => tddParamOutShapeComposition($data, ['id' => 10, 'name' => 'Alice', 'extra' => true])) - ->toThrow(TypeError::class, "Argument &\$data (param-out) contains unsealed unexpected key 'extra'"); + expect(fn () => tddParamOutShapeComposition($data, ['id' => 10, 'name' => 'Alice', 'extra' => true])) + ->toThrow(TypeError::class, "Argument &\$data (param-out) contains unsealed unexpected key 'extra'") + ; }); }); @@ -588,40 +606,45 @@ public function mutateFlagBeforeExit(bool $asInt, mixed &$out, mixed $newVal): v $a = new Issue1SingleLineParamOutA(); $v = 1; - expect(fn() => $a->run($v)) - ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int'); + expect(fn () => $a->run($v)) + ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int') + ; }); test('Class B: single-line @param and @param-out with &$x ampersand throws TypeError', function () { $b = new Issue1SingleLineAmpersandB(); $v = 1; - expect(fn() => $b->run($v)) - ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int'); + expect(fn () => $b->run($v)) + ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int') + ; }); test('Class C: single-line @param, @param-out, and @return throws TypeError', function () { $c = new Issue1SingleLineWithReturnC(); $v = 1; - expect(fn() => $c->run($v)) - ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int'); + expect(fn () => $c->run($v)) + ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int') + ; }); test('Class D: single-line @param and @phpstan-param-out throws TypeError', function () { $d = new Issue1SingleLinePhpstanD(); $v = 1; - expect(fn() => $d->run($v)) - ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int'); + expect(fn () => $d->run($v)) + ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int') + ; }); test('Class E: multi-line @param-out with &$x ampersand throws TypeError', function () { $e = new Issue1MultiLineAmpersandE(); $v = 1; - expect(fn() => $e->run($v)) - ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int'); + expect(fn () => $e->run($v)) + ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int') + ; }); }); @@ -630,15 +653,17 @@ public function mutateFlagBeforeExit(bool $asInt, mixed &$out, mixed $newVal): v $service = new Issue2GenericMethodWithParamOut(); $v = 42; - expect(fn() => $service->run($v)) - ->toThrow(TypeError::class, 'Return value must be of type int'); + expect(fn () => $service->run($v)) + ->toThrow(TypeError::class, 'Return value must be of type int') + ; }); test('enforces generic @return T after @param-out check passes on standalone function', function () { $v = 42; - expect(fn() => issue2StandaloneGenericWithParamOut($v)) - ->toThrow(TypeError::class, 'Return value must be of type int'); + expect(fn () => issue2StandaloneGenericWithParamOut($v)) + ->toThrow(TypeError::class, 'Return value must be of type int') + ; }); test('preserves generic template T across multiple sequential @param-out checks in the same method', function () { @@ -646,8 +671,9 @@ public function mutateFlagBeforeExit(bool $asInt, mixed &$out, mixed $newVal): v $first = 42; $second = 100; - expect(fn() => $service->syncBoth($first, $second)) - ->toThrow(TypeError::class, 'Argument &$second (param-out) must be of type int'); + expect(fn () => $service->syncBoth($first, $second)) + ->toThrow(TypeError::class, 'Argument &$second (param-out) must be of type int') + ; }); }); @@ -668,8 +694,9 @@ public function mutateFlagBeforeExit(bool $asInt, mixed &$out, mixed $newVal): v $gen = $service->runInvalidBeforeYield($x); - expect(fn() => $gen->current()) - ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int'); + expect(fn () => $gen->current()) + ->toThrow(TypeError::class, 'Argument &$x (param-out) must be of type int') + ; }); test('throws TypeError when generator mutates by-ref param to invalid type after yield before finishing', function () { @@ -700,8 +727,9 @@ public function mutateFlagBeforeExit(bool $asInt, mixed &$out, mixed $newVal): v tddParamOutConditionalByFlag(true, $out, 42); expect($out)->toBe(42); - expect(fn() => tddParamOutConditionalByFlag(true, $out, -10)) - ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type positive-int'); + expect(fn () => tddParamOutConditionalByFlag(true, $out, -10)) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type positive-int') + ; }); test('evaluates else branch (non-empty-string) on standalone function when $asInt is false', function () { @@ -709,8 +737,9 @@ public function mutateFlagBeforeExit(bool $asInt, mixed &$out, mixed $newVal): v tddParamOutConditionalByFlag(false, $out, 'valid_text'); expect($out)->toBe('valid_text'); - expect(fn() => tddParamOutConditionalByFlag(false, $out, '')) - ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type non-empty-string'); + expect(fn () => tddParamOutConditionalByFlag(false, $out, '')) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type non-empty-string') + ; }); test('evaluates parameter-based conditional @param-out on class methods and preserves entry argument on in-body mutation', function () { @@ -720,19 +749,21 @@ public function mutateFlagBeforeExit(bool $asInt, mixed &$out, mixed $newVal): v $service->formatOutput('int', $out, 100); expect($out)->toBe(100); - expect(fn() => $service->formatOutput('int', $out, -5)) - ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type positive-int'); + expect(fn () => $service->formatOutput('int', $out, -5)) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type positive-int') + ; $service->formatOutput('string', $out, 'hello'); expect($out)->toBe('hello'); - expect(fn() => $service->formatOutput('string', $out, '')) - ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type non-empty-string'); + expect(fn () => $service->formatOutput('string', $out, '')) + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type non-empty-string') + ; $service->mutateFlagBeforeExit(true, $out, 50); expect($out)->toBe(50); - expect(fn() => $service->mutateFlagBeforeExit(true, $out, 'wrong_branch')) + expect(fn () => $service->mutateFlagBeforeExit(true, $out, 'wrong_branch')) ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type positive-int'); }); }); diff --git a/tests/TypeChecking/CallablesAndIterators/GenericIteratorsAndGeneratorsTest.php b/tests/TypeChecking/CallablesAndIterators/GenericIteratorsAndGeneratorsTest.php index 9189cf59..0012de0a 100644 --- a/tests/TypeChecking/CallablesAndIterators/GenericIteratorsAndGeneratorsTest.php +++ b/tests/TypeChecking/CallablesAndIterators/GenericIteratorsAndGeneratorsTest.php @@ -208,16 +208,18 @@ function testConditionalIterableParam(iterable $stream, mixed $sample = null): a $gen->current(); - expect(fn() => $gen->send('invalid')) - ->toThrow(TypeError::class, 'must be of type int'); + expect(fn () => $gen->send('invalid')) + ->toThrow(TypeError::class, 'must be of type int') + ; }); test('strictly enforces TSend = void and throws TypeError when non-null value is sent into generator', function () { $g = (new D2GeneratorFixture())->run(); $g->current(); - expect(fn() => $g->send('not null')) - ->toThrow(TypeError::class, 'Generator sent value (TSend) must be of type void, string \'not null\' given'); + expect(fn () => $g->send('not null')) + ->toThrow(TypeError::class, 'Generator sent value (TSend) must be of type void, string \'not null\' given') + ; }); test('allows standard foreach iteration on generator with TSend = void', function () { @@ -266,15 +268,17 @@ function testConditionalIterableParam(iterable $stream, mixed $sample = null): a expect(iterator_to_array($validIntGen))->toBe([0 => 42]); $badIntGen = testConditionalGeneratorReturn(null, -10); - expect(fn() => iterator_to_array($badIntGen)) - ->toThrow(TypeError::class, 'Return iterator value must be of type positive-int'); + expect(fn () => iterator_to_array($badIntGen)) + ->toThrow(TypeError::class, 'Return iterator value must be of type positive-int') + ; $validStrGen = testConditionalGeneratorReturn('override', 'hello'); expect(iterator_to_array($validStrGen))->toBe([0 => 'hello']); $badStrGen = testConditionalGeneratorReturn('override', ''); - expect(fn() => iterator_to_array($badStrGen)) - ->toThrow(TypeError::class, 'Return iterator value must be of type non-empty-string'); + expect(fn () => iterator_to_array($badStrGen)) + ->toThrow(TypeError::class, 'Return iterator value must be of type non-empty-string') + ; }); test('validates nested conditional element inside Generator', function () { @@ -282,12 +286,14 @@ function testConditionalIterableParam(iterable $stream, mixed $sample = null): a expect(iterator_to_array($validGen))->toBe([0 => 100]); $badGen = testNestedConditionalGeneratorReturn(null, -5); - expect(fn() => iterator_to_array($badGen)) - ->toThrow(TypeError::class, 'Return iterator value must be of type positive-int'); + expect(fn () => iterator_to_array($badGen)) + ->toThrow(TypeError::class, 'Return iterator value must be of type positive-int') + ; $badStrGen = testNestedConditionalGeneratorReturn('override', ''); - expect(fn() => iterator_to_array($badStrGen)) - ->toThrow(TypeError::class, 'Return iterator value must be of type non-empty-string'); + expect(fn () => iterator_to_array($badStrGen)) + ->toThrow(TypeError::class, 'Return iterator value must be of type non-empty-string') + ; }); test('lazily validates conditional iterable parameter on Traversable iteration', function () { @@ -295,11 +301,12 @@ function testConditionalIterableParam(iterable $stream, mixed $sample = null): a expect(testConditionalIterableParam($validIter))->toBe([10, 20, 30]); $badIntIter = new ArrayIterator([10, -5, 30]); - expect(fn() => testConditionalIterableParam($badIntIter)) - ->toThrow(TypeError::class, 'Iterator $stream value must be of type positive-int'); + expect(fn () => testConditionalIterableParam($badIntIter)) + ->toThrow(TypeError::class, 'Iterator $stream value must be of type positive-int') + ; $badStrIter = new ArrayIterator(['valid', '']); - expect(fn() => testConditionalIterableParam($badStrIter, 'override')) + expect(fn () => testConditionalIterableParam($badStrIter, 'override')) ->toThrow(TypeError::class, 'Iterator $stream value must be of type non-empty-string'); }); }); diff --git a/tests/TypeChecking/Generics/DefaultTemplateTypesTest.php b/tests/TypeChecking/Generics/DefaultTemplateTypesTest.php index c3c5d329..1e63b705 100644 --- a/tests/TypeChecking/Generics/DefaultTemplateTypesTest.php +++ b/tests/TypeChecking/Generics/DefaultTemplateTypesTest.php @@ -205,6 +205,60 @@ public function put(mixed $key, mixed $val): void } } +/** + * Class with static methods and class-level template default + * + * @template T = int + */ +class DefaultStaticClassHolder +{ + /** + * @return T + */ + public static function getDefault(): mixed + { + return 'not_an_int'; + } + + /** + * @param T $val + */ + public static function checkDefaultParam(mixed $val): mixed + { + return $val; + } +} + +/** + * Class with 0-arg method and typestate self-out + * + * @template T = int + */ +class DefaultTypestateZeroArgHolder +{ + /** + * @var T|null + */ + public mixed $val = null; + + /** + * 0-argument method with @self-out + * + * @self-out self + */ + public function enableString(): void + { + } + + /** + * @param T $v + */ + public function set(mixed $v): void + { + $this->val = $v; + } +} + describe('Default Template Annotations (@template T = DefaultType)', function () { describe('1. Standalone Function Default Templates', function () { test('uses default template type string when template T is unbound', function () { @@ -443,7 +497,6 @@ public function put(mixed $key, mixed $val): void ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type positive-int') ; - // Overriding T = string by passing 'sample_str' testDefaultTemplateConditionalParamOut($out, 'hello', 'sample_str'); expect($out)->toBe('hello'); @@ -452,4 +505,46 @@ public function put(mixed $key, mixed $val): void ; }); }); + + describe('7. TemplateManager Consistency on Unannotated Instances & Static Classes', function () { + test('getBoundTemplates, isBound, and getBoundType return default T = int on unannotated instance with 0-arg method', function () { + $box = new DefaultIntBox(); + $templates = ['T' => new PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode('T', null, '', new PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode('int'))]; + + $bound = \TypePHP\Internal\Generics\TemplateManager::getBoundTemplates(DefaultIntBox::class . '::computeOne', $box, $templates); + expect($bound)->toHaveKey('T') + ->and((string) $bound['T'])->toBe('int') + ; + + expect(\TypePHP\Internal\Generics\TemplateManager::isBound(DefaultIntBox::class . '::computeOne', $box, 'T'))->toBeTrue() + ->and((string) \TypePHP\Internal\Generics\TemplateManager::getBoundType(DefaultIntBox::class . '::computeOne', $box, 'T'))->toBe('int') + ; + }); + + test('enforces default template T = int on static method parameters and return types', function () { + expect(fn () => DefaultStaticClassHolder::checkDefaultParam('wrong_type')) + ->toThrow(TypeError::class, 'must be of type int') + ; + + expect(DefaultStaticClassHolder::checkDefaultParam(42))->toBe(42); + + expect(fn () => DefaultStaticClassHolder::getDefault()) + ->toThrow(TypeError::class, 'Return value must be of type int') + ; + }); + + test('preserves default T = int across 0-argument @self-out method call', function () { + $holder = new DefaultTypestateZeroArgHolder(); + + $holder->enableString(); + + expect(TypePHP::getGenericType($holder))->toBe('(int | string)'); + + $holder->set(42); + $holder->set('now_allowed_string'); + + expect(fn () => $holder->set(new stdClass())) + ->toThrow(TypeError::class, 'must be of type (int | string)'); + }); + }); }); diff --git a/tests/TypeChecking/Generics/FBoundedPolymorphismTest.php b/tests/TypeChecking/Generics/FBoundedPolymorphismTest.php index 18f553d5..7c0dcf7f 100644 --- a/tests/TypeChecking/Generics/FBoundedPolymorphismTest.php +++ b/tests/TypeChecking/Generics/FBoundedPolymorphismTest.php @@ -366,4 +366,4 @@ public function compareTo(mixed $other): int ; }); }); -}); \ No newline at end of file +}); From ccd00b7dd652c2a86dd4eb90b871789196da342b Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sun, 8 Nov 2026 21:57:41 +0800 Subject: [PATCH 07/11] Enhance type handling and add support for generics in various checkers and tests --- src/Internal/Ast/ContractVisitor.php | 84 +++-- src/Internal/Ast/TypeDeducer.php | 91 ++++- src/Internal/Checker/InlineChecker.php | 10 +- src/Internal/Checker/MemberAssignChecker.php | 4 +- .../Boundaries/ParamOutContractsTest.php | 3 +- .../PropertyReferenceAssignmentTest.php | 328 ++++++++++++++++++ .../GenericIteratorsAndGeneratorsTest.php | 3 +- .../Generics/DefaultTemplateTypesTest.php | 3 +- 8 files changed, 496 insertions(+), 30 deletions(-) diff --git a/src/Internal/Ast/ContractVisitor.php b/src/Internal/Ast/ContractVisitor.php index 90579437..d2ac3407 100644 --- a/src/Internal/Ast/ContractVisitor.php +++ b/src/Internal/Ast/ContractVisitor.php @@ -82,6 +82,11 @@ final class ContractVisitor extends NodeVisitorAbstract */ private array $byRefStack = []; + /** + * @var array> + */ + private array $localClassTemplates = []; + public function __construct(private string $currentFile = '') { $this->scopeManager = new ScopeManager(); @@ -616,7 +621,6 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ $hasPropertyWithDoc = false; $isReadonly = false; $isFinal = false; - $hasTemplates = false; $doc = $node->getDocComment(); if ($doc === null && $typeName !== null && StubManager::hasClassStub($typeName)) { @@ -626,6 +630,30 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ } } + $templates = []; + if ($doc !== null && ( + str_contains($doc->getText(), '@template') + || str_contains($doc->getText(), '@phpstan-template') + || str_contains($doc->getText(), '@psalm-template') + )) { + try { + $phpDocNode = DocblockExtractor::parseDocString($doc->getText()); + $templates = DocblockExtractor::extractTemplates($phpDocNode); + } catch (\Throwable) { + } + } + $hasTemplates = $templates !== []; + + if ($hasTemplates) { + $templateNames = array_keys($templates); + if ($typeName !== null) { + $this->localClassTemplates[$typeName] = $templateNames; + } + if ($shortName !== null) { + $this->localClassTemplates[$shortName] = $templateNames; + } + } + if ($node instanceof Node\Stmt\Class_) { $hasExtends = $node->extends !== null; $hasImplements = $node->implements !== []; @@ -639,8 +667,10 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ } elseif ($stmt instanceof Node\Stmt\Property && $stmt->getDocComment() !== null) { $hasPropertyWithDoc = true; } elseif ($stmt instanceof Node\Stmt\ClassMethod && strtolower($stmt->name->toString()) === '__construct') { + $ctorDoc = $stmt->getDocComment(); + $hasParamInCtor = $ctorDoc !== null && str_contains($ctorDoc->getText(), '@param'); foreach ($stmt->params as $param) { - if ($param->isPromoted() && $param->getDocComment() !== null) { + if ($param->isPromoted() && ($param->getDocComment() !== null || $hasParamInCtor)) { $hasPropertyWithDoc = true; break; @@ -649,11 +679,6 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ } } - $hasTemplates = $doc !== null && ( - str_contains($doc->getText(), '@template') - || str_contains($doc->getText(), '@phpstan-template') - || str_contains($doc->getText(), '@psalm-template') - ); $hasClassDoc = $doc !== null && ( $hasTemplates || str_contains($doc->getText(), '@phpstan-') @@ -667,12 +692,6 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ } elseif ($node instanceof Node\Stmt\Enum_) { $hasRealInheritance = $node->implements !== []; $hasInheritance = $hasRealInheritance; - } else { - $hasTemplates = $doc !== null && ( - str_contains($doc->getText(), '@template') - || str_contains($doc->getText(), '@phpstan-template') - || str_contains($doc->getText(), '@psalm-template') - ); } if ($typeName !== null && ($node instanceof Node\Stmt\Class_ || $node instanceof Node\Stmt\Trait_)) { @@ -692,16 +711,31 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ } } } elseif ($stmt instanceof Node\Stmt\ClassMethod && strtolower($stmt->name->toString()) === '__construct') { + $methodDoc = $stmt->getDocComment(); + $methodParamTags = null; + if ($methodDoc !== null && str_contains($methodDoc->getText(), '@param')) { + try { + $methodPhpDoc = DocblockExtractor::parseDocString($methodDoc->getText()); + $methodParamTags = DocblockExtractor::getParamTags($methodPhpDoc); + } catch (\Throwable) { + } + } + foreach ($stmt->params as $p) { if ($p->isPromoted() && $p->var instanceof Node\Expr\Variable && \is_string($p->var->name)) { - $doc = $p->getDocComment(); - if ($doc !== null) { - $pType = DocblockExtractor::extractTypeFromPropertyDoc($doc->getText(), $p->var->name); - if ($pType !== null) { - $this->localClassPropertyTypes[$typeName][$p->var->name] = (string) $pType; - if ($shortName !== null) { - $this->localClassPropertyTypes[$shortName][$p->var->name] = (string) $pType; - } + $paramName = $p->var->name; + $pType = null; + $paramDoc = $p->getDocComment(); + if ($paramDoc !== null) { + $pType = DocblockExtractor::extractTypeFromPropertyDoc($paramDoc->getText(), $paramName); + } + if ($pType === null && $methodParamTags !== null && isset($methodParamTags[$paramName])) { + $pType = $methodParamTags[$paramName]->type; + } + if ($pType !== null) { + $this->localClassPropertyTypes[$typeName][$paramName] = (string) $pType; + if ($shortName !== null) { + $this->localClassPropertyTypes[$shortName][$paramName] = (string) $pType; } } } @@ -1136,7 +1170,13 @@ private function deduceMemberChainType(string $rootType, array $chain): ?string if (isset($this->localClassPropertyTypes[$deducedType][$propName])) { $deducedType = $this->localClassPropertyTypes[$deducedType][$propName]; } else { - $deducedType = TypeDeducer::deducePropertyType($deducedType, $propName); + $deducedType = TypeDeducer::deducePropertyType( + $deducedType, + $propName, + $this->localClassPropertyTypes, + $this->localClassTemplates, + $this->currentFile + ); } if ($deducedType === null) { return null; diff --git a/src/Internal/Ast/TypeDeducer.php b/src/Internal/Ast/TypeDeducer.php index 6e5f61ce..ff41ed8d 100644 --- a/src/Internal/Ast/TypeDeducer.php +++ b/src/Internal/Ast/TypeDeducer.php @@ -20,6 +20,8 @@ use TypePHP\Internal\Docblock\DocblockExtractor; use TypePHP\Internal\Docblock\DocblockNormalizer; use TypePHP\Internal\Docblock\DocblockParser; +use TypePHP\Internal\Generics\TemplateSubstitutor; +use TypePHP\Internal\Resolver\SpecialTypeResolver; /** * Deduces element, key, and indexed member types from container type strings. @@ -173,9 +175,17 @@ public static function deduceDimType(string $containerTypeString, ?Expr $dimExpr /** * Deduces the property type of an object shape or class property access ($obj->prop). + * + * @param array> $localPropertyTypes + * @param array> $localClassTemplates */ - public static function deducePropertyType(string $containerTypeString, string $propName): ?string - { + public static function deducePropertyType( + string $containerTypeString, + string $propName, + array $localPropertyTypes = [], + array $localClassTemplates = [], + string $currentFile = '' + ): ?string { $typeNode = self::parseTypeString($containerTypeString); if ($typeNode === null) { return null; @@ -185,6 +195,10 @@ public static function deducePropertyType(string $containerTypeString, string $p $typeNode = $typeNode->type; } + if ($currentFile !== '') { + $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $currentFile); + } + if ($typeNode instanceof ObjectShapeNode) { foreach ($typeNode->items as $item) { $name = $item->keyName instanceof IdentifierTypeNode @@ -199,6 +213,15 @@ public static function deducePropertyType(string $containerTypeString, string $p if ($typeNode instanceof IdentifierTypeNode) { $className = $typeNode->name; + $shortName = ($pos = strrpos($className, '\\')) !== false ? substr($className, $pos + 1) : $className; + + if (isset($localPropertyTypes[$className][$propName])) { + return $localPropertyTypes[$className][$propName]; + } + if (isset($localPropertyTypes[$shortName][$propName])) { + return $localPropertyTypes[$shortName][$propName]; + } + if ( class_exists($className, false) || class_exists($className) || interface_exists($className, false) || interface_exists($className) @@ -211,6 +234,70 @@ class_exists($className, false) || class_exists($className) } } + if ($typeNode instanceof GenericTypeNode) { + $baseType = $typeNode->type; + $className = $baseType instanceof IdentifierTypeNode ? $baseType->name : (string) $baseType; + $shortName = ($pos = strrpos($className, '\\')) !== false ? substr($className, $pos + 1) : $className; + + $rawPropType = null; + $templateNames = null; + + if (isset($localPropertyTypes[$className][$propName])) { + $rawPropType = $localPropertyTypes[$className][$propName]; + $templateNames = $localClassTemplates[$className] ?? ($localClassTemplates[$shortName] ?? null); + } elseif (isset($localPropertyTypes[$shortName][$propName])) { + $rawPropType = $localPropertyTypes[$shortName][$propName]; + $templateNames = $localClassTemplates[$shortName] ?? ($localClassTemplates[$className] ?? null); + } + + if ($rawPropType === null) { + if ( + class_exists($className, false) || class_exists($className) + || interface_exists($className, false) || interface_exists($className) + || trait_exists($className, false) || trait_exists($className) + ) { + $parsedProp = DocblockParser::parseProperty($className, $propName); + if ($parsedProp !== null) { + $rawPropType = $parsedProp; + } + $templates = DocblockParser::parseClassTemplates($className); + if ($templates !== []) { + $templateNames = array_keys($templates); + } + } + } + + if ($rawPropType !== null) { + $propTypeNode = \is_string($rawPropType) ? self::parseTypeString($rawPropType) : $rawPropType; + if ($propTypeNode === null) { + return \is_string($rawPropType) ? $rawPropType : (string) $rawPropType; + } + + if ($templateNames !== null && $templateNames !== []) { + $bindings = []; + if (\count($templateNames) === 2 && \count($typeNode->genericTypes) === 1) { + $firstLower = strtolower($templateNames[0]); + if ($firstLower === 'k' || $firstLower === 'tkey' || $firstLower === 'key') { + $bindings[$templateNames[0]] = new IdentifierTypeNode('array-key'); + $bindings[$templateNames[1]] = $typeNode->genericTypes[0]; + } + } else { + foreach ($templateNames as $idx => $tName) { + if (isset($typeNode->genericTypes[$idx])) { + $bindings[$tName] = $typeNode->genericTypes[$idx]; + } + } + } + + if ($bindings !== []) { + $propTypeNode = TemplateSubstitutor::substitute($propTypeNode, $bindings); + } + } + + return (string) $propTypeNode; + } + } + return null; } diff --git a/src/Internal/Checker/InlineChecker.php b/src/Internal/Checker/InlineChecker.php index 5b719f9c..62437a39 100644 --- a/src/Internal/Checker/InlineChecker.php +++ b/src/Internal/Checker/InlineChecker.php @@ -238,7 +238,9 @@ public static function validateCollectionElementMutation( string $typeString, string $varName, string $file, - TypeValidatorRegistry $registry + TypeValidatorRegistry $registry, + ?string $caller = null, + mixed $thisOrClass = null ): ?ErrorMessage { if (\count($path) !== 1 || $path[0][0] !== 'dim') { return null; @@ -246,12 +248,16 @@ public static function validateCollectionElementMutation( try { $normalized = DocblockNormalizer::normalize($typeString); - [$typeNode] = self::parseTypeString($normalized); + [$typeNode, $needsContext] = self::parseTypeString($normalized); if ($file !== '') { $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $file); } + if ($needsContext && $caller !== null) { + $typeNode = self::resolveCallerContext($typeNode, $caller, $thisOrClass); + } + $key = $path[0][1]; $keyStr = \is_string($key) ? $key : (\is_int($key) ? (string) $key : ''); diff --git a/src/Internal/Checker/MemberAssignChecker.php b/src/Internal/Checker/MemberAssignChecker.php index 85b416d9..2374a28f 100644 --- a/src/Internal/Checker/MemberAssignChecker.php +++ b/src/Internal/Checker/MemberAssignChecker.php @@ -54,7 +54,9 @@ public static function check( $typeString, $varName, $file, - $registry + $registry, + $caller, + $thisOrClass ); if ($directErr instanceof ErrorMessage) { diff --git a/tests/TypeChecking/Boundaries/ParamOutContractsTest.php b/tests/TypeChecking/Boundaries/ParamOutContractsTest.php index 28e22187..3b5d8ec8 100644 --- a/tests/TypeChecking/Boundaries/ParamOutContractsTest.php +++ b/tests/TypeChecking/Boundaries/ParamOutContractsTest.php @@ -764,7 +764,8 @@ public function mutateFlagBeforeExit(bool $asInt, mixed &$out, mixed $newVal): v expect($out)->toBe(50); expect(fn () => $service->mutateFlagBeforeExit(true, $out, 'wrong_branch')) - ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type positive-int'); + ->toThrow(TypeError::class, 'Argument &$out (param-out) must be of type positive-int') + ; }); }); }); diff --git a/tests/TypeChecking/Boundaries/PropertyReferenceAssignmentTest.php b/tests/TypeChecking/Boundaries/PropertyReferenceAssignmentTest.php index fd8855c4..eba6db1b 100644 --- a/tests/TypeChecking/Boundaries/PropertyReferenceAssignmentTest.php +++ b/tests/TypeChecking/Boundaries/PropertyReferenceAssignmentTest.php @@ -5,6 +5,9 @@ namespace TypePHP\Tests\TypeChecking\Boundaries; use TypePHP\Exception\TypeError; +use TypePHP\Tests\Fixtures\Domain\Car; +use TypePHP\Tests\Fixtures\Domain\Dog; +use TypePHP\Tests\Fixtures\Generics\GenericBox; use TypePHP\Tests\Fixtures\Properties\PropertyRefTargetFixture; /** @@ -38,6 +41,133 @@ public function mutateInternalScoreByRef(mixed $val): void } } +class GenericRefUser +{ + public function __construct(public string $name = 'Alice') + { + } +} + +class GenericRefProduct +{ + public function __construct(public string $sku = 'PROD-1') + { + } +} + +/** + * @template T + */ +class SameFileGenericBox +{ + /** + * @param T $value + */ + public function __construct( + public mixed $value + ) { + } + + public function mutateInternalValueByRef(mixed $val): void + { + $ref = &$this->value; + $ref = $val; + } +} + +/** + * @template K of array-key + * @template V + */ +class SameFileGenericMap +{ + /** + * @param K $key + * @param V $val + */ + public function __construct( + public mixed $key, + public mixed $val + ) { + } +} + +/** + * Generic fixture with list property + * + * @template T + */ +class GenericListBoxFixture +{ + /** + * @var list + */ + public array $items = []; + + /** + * @param list $items + */ + public function __construct(array $items = []) + { + $this->items = $items; + } + + public function mutateItemByRef(int $index, mixed $val): void + { + $ref = &$this->items[$index]; + $ref = $val; + } + + public function appendItemViaRef(mixed $val): void + { + $ref = &$this->items; + $ref[] = $val; + } +} + +/** + * Generic fixture with typed array T[] property + * + * @template T + */ +class GenericTypedArrayBoxFixture +{ + /** + * @var T[] + */ + public array $items = []; + + /** + * @param T[] $items + */ + public function __construct(array $items = []) + { + $this->items = $items; + } +} + +/** + * Generic fixture with array map property + * + * @template K of array-key + * @template V + */ +class GenericMapBoxFixture +{ + /** + * @var array + */ + public array $items = []; + + /** + * @param array $items + */ + public function __construct(array $items = []) + { + $this->items = $items; + } +} + describe('By-Reference Property Aliasing ($ref = &$obj->prop)', function () { beforeEach(function () { PropertyRefTargetFixture::reset(); @@ -202,4 +332,202 @@ public function mutateInternalScoreByRef(mixed $val): void expect($local->localScore)->toBe(10); }); }); + + describe('7. Generic Property Reference Aliasing ($ref = &$genericBox->item)', function () { + test('throws TypeError when assigning invalid value to reference aliasing a generic property (GenericBox)', function () { + /** @var GenericBox $dogBox */ + $dogBox = new GenericBox(); + $dogBox->item = new Dog(); + + $ref = &$dogBox->item; + + expect(function () use (&$ref) { + $ref = new Car(); + })->toThrow(TypeError::class, Dog::class); + }); + + test('allows valid assignment to reference aliasing a generic property and mutates property in place', function () { + /** @var GenericBox $dogBox */ + $dogBox = new GenericBox(); + $dogBox->item = new Dog(); + + $ref = &$dogBox->item; + $newDog = new Dog(); + $ref = $newDog; + + expect($dogBox->item)->toBe($newDog) + ->and($ref)->toBe($newDog) + ; + }); + + test('throws TypeError when assigning invalid value to reference aliasing a promoted generic property (User Bug Reproduction)', function () { + /** @var SameFileGenericBox $userBox */ + $userBox = new SameFileGenericBox(new GenericRefUser()); + + $reference = &$userBox->value; + + expect(function () use (&$reference) { + $reference = new GenericRefProduct(); + })->toThrow(TypeError::class, GenericRefUser::class); + }); + + test('throws TypeError when assigning invalid value to reference aliasing multi-template generic property', function () { + /** @var SameFileGenericMap $map */ + $map = new SameFileGenericMap('timeout', 10); + + $keyRef = &$map->key; + $valRef = &$map->val; + + expect(function () use (&$valRef) { + $valRef = -50; + })->toThrow(TypeError::class, 'positive-int'); + + expect(function () use (&$keyRef) { + $keyRef = 12345; + })->toThrow(TypeError::class, 'must be of type string'); + }); + + test('throws TypeError when internal method mutates generic $this property via reference alias', function () { + /** @var SameFileGenericBox $userBox */ + $userBox = new SameFileGenericBox(new GenericRefUser()); + + expect(function () use ($userBox) { + $userBox->mutateInternalValueByRef(new GenericRefProduct()); + })->toThrow(TypeError::class, GenericRefUser::class); + + expect($userBox->value)->toBeInstanceOf(GenericRefUser::class); + }); + }); + + describe('8. Generic Array Properties: By-Reference Aliasing & Element Mutations', function () { + test('throws TypeError when assigning invalid value to reference aliasing an element of generic list', function () { + /** @var GenericListBoxFixture $box */ + $box = new GenericListBoxFixture([new Dog()]); + + $ref = &$box->items[0]; + + expect(function () use (&$ref) { + $ref = new Car(); + })->toThrow(TypeError::class, Dog::class); + + expect($box->items[0])->toBeInstanceOf(Dog::class); + }); + + test('throws TypeError when assigning invalid value to reference aliasing an element of generic T[]', function () { + /** @var GenericTypedArrayBoxFixture $box */ + $box = new GenericTypedArrayBoxFixture([new Dog()]); + + $ref = &$box->items[0]; + + expect(function () use (&$ref) { + $ref = new Car(); + })->toThrow(TypeError::class, Dog::class); + + expect($box->items[0])->toBeInstanceOf(Dog::class); + }); + + test('throws TypeError when assigning invalid value to reference aliasing an element of generic array', function () { + /** @var GenericMapBoxFixture $box */ + $box = new GenericMapBoxFixture(['pet' => new Dog()]); + + $ref = &$box->items['pet']; + + expect(function () use (&$ref) { + $ref = new Car(); + })->toThrow(TypeError::class, Dog::class); + + expect($box->items['pet'])->toBeInstanceOf(Dog::class); + }); + + test('throws TypeError when appending invalid value to reference aliasing the entire generic array property', function () { + /** @var GenericListBoxFixture $box */ + $box = new GenericListBoxFixture([new Dog()]); + + $ref = &$box->items; + + expect(function () use (&$ref) { + $ref[] = new Car(); + })->toThrow(TypeError::class, Dog::class); + + expect($box->items)->toHaveCount(1); + }); + + test('throws TypeError when assigning by index to reference aliasing the entire generic array property', function () { + /** @var GenericListBoxFixture $box */ + $box = new GenericListBoxFixture([new Dog()]); + + $ref = &$box->items; + + expect(function () use (&$ref) { + $ref[0] = new Car(); + })->toThrow(TypeError::class, Dog::class); + + expect($box->items[0])->toBeInstanceOf(Dog::class); + }); + + test('throws TypeError on direct array append to generic property ($box->items[] = new Car())', function () { + /** @var GenericListBoxFixture $box */ + $box = new GenericListBoxFixture(); + + expect(function () use ($box) { + $box->items[] = new Car(); + })->toThrow(TypeError::class, Dog::class); + + expect($box->items)->toBeEmpty(); + }); + + test('throws TypeError on direct index assignment to generic property ($box->items[0] = new Car())', function () { + /** @var GenericListBoxFixture $box */ + $box = new GenericListBoxFixture([new Dog()]); + + expect(function () use ($box) { + $box->items[0] = new Car(); + })->toThrow(TypeError::class, Dog::class); + + expect($box->items[0])->toBeInstanceOf(Dog::class); + }); + + test('throws TypeError when internal method mutates generic $this array element via reference alias', function () { + /** @var GenericListBoxFixture $box */ + $box = new GenericListBoxFixture([new Dog()]); + + expect(function () use ($box) { + $box->mutateItemByRef(0, new Car()); + })->toThrow(TypeError::class, Dog::class); + + expect($box->items[0])->toBeInstanceOf(Dog::class); + }); + + test('throws TypeError when internal method appends to generic $this array via reference alias', function () { + /** @var GenericListBoxFixture $box */ + $box = new GenericListBoxFixture([new Dog()]); + + expect(function () use ($box) { + $box->appendItemViaRef(new Car()); + })->toThrow(TypeError::class, Dog::class); + + expect($box->items)->toHaveCount(1); + }); + + test('allows valid assignment to generic array element reference and mutates in place', function () { + /** @var GenericListBoxFixture $box */ + $box = new GenericListBoxFixture([new Dog()]); + + $ref = &$box->items[0]; + $newDog = new Dog(); + $ref = $newDog; + + expect($box->items[0])->toBe($newDog) + ->and($ref)->toBe($newDog) + ; + + $arrayRef = &$box->items; + $buddy = new Dog(); + $arrayRef[] = $buddy; + + expect($box->items)->toHaveCount(2) + ->and($box->items[1])->toBe($buddy) + ; + }); + }); }); diff --git a/tests/TypeChecking/CallablesAndIterators/GenericIteratorsAndGeneratorsTest.php b/tests/TypeChecking/CallablesAndIterators/GenericIteratorsAndGeneratorsTest.php index 0012de0a..f9637230 100644 --- a/tests/TypeChecking/CallablesAndIterators/GenericIteratorsAndGeneratorsTest.php +++ b/tests/TypeChecking/CallablesAndIterators/GenericIteratorsAndGeneratorsTest.php @@ -307,7 +307,8 @@ function testConditionalIterableParam(iterable $stream, mixed $sample = null): a $badStrIter = new ArrayIterator(['valid', '']); expect(fn () => testConditionalIterableParam($badStrIter, 'override')) - ->toThrow(TypeError::class, 'Iterator $stream value must be of type non-empty-string'); + ->toThrow(TypeError::class, 'Iterator $stream value must be of type non-empty-string') + ; }); }); }); diff --git a/tests/TypeChecking/Generics/DefaultTemplateTypesTest.php b/tests/TypeChecking/Generics/DefaultTemplateTypesTest.php index 1e63b705..fed90015 100644 --- a/tests/TypeChecking/Generics/DefaultTemplateTypesTest.php +++ b/tests/TypeChecking/Generics/DefaultTemplateTypesTest.php @@ -544,7 +544,8 @@ public function set(mixed $v): void $holder->set('now_allowed_string'); expect(fn () => $holder->set(new stdClass())) - ->toThrow(TypeError::class, 'must be of type (int | string)'); + ->toThrow(TypeError::class, 'must be of type (int | string)') + ; }); }); }); From 70676694612aa06b05fd2bca281b770d20d422c9 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Sun, 8 Nov 2026 23:54:53 +0800 Subject: [PATCH 08/11] Enhance constant validation by adding checks for class and global constants, including tests for contract compliance and error handling --- src/Internal/Ast/ContractVisitor.php | 135 +++++++- src/Internal/Ast/NodeBuilder.php | 18 ++ src/Internal/Reporting/ViolationCollector.php | 2 +- src/Internal/Reporting/ViolationRecord.php | 5 +- src/Internal/RuntimeTypeChecker.php | 45 +++ tests/Internal/Ast/NodeBuilderTest.php | 16 + tests/Internal/RuntimeTypeCheckerTest.php | 107 ++++--- .../Boundaries/ConstantContractsTest.php | 287 ++++++++++++++++++ 8 files changed, 565 insertions(+), 50 deletions(-) create mode 100644 tests/TypeChecking/Boundaries/ConstantContractsTest.php diff --git a/src/Internal/Ast/ContractVisitor.php b/src/Internal/Ast/ContractVisitor.php index d2ac3407..eeb8b687 100644 --- a/src/Internal/Ast/ContractVisitor.php +++ b/src/Internal/Ast/ContractVisitor.php @@ -213,6 +213,23 @@ public function leaveNode(Node $node): Node|array|null { $this->trackDeclarationExit($node); + if ($node instanceof Node\Stmt\Class_ && $node->name !== null) { + $className = $this->resolveQualifiedName($node->name); + if ($className !== null) { + $constChecks = $this->collectUnprovenClassConstantChecks($node, $className); + if ($constChecks !== []) { + return [$node, ...$constChecks]; + } + } + } + + if ($node instanceof Node\Stmt\Const_) { + $globalConstChecks = $this->collectUnprovenGlobalConstantChecks($node); + if ($globalConstChecks !== []) { + return [$node, ...$globalConstChecks]; + } + } + if ($node instanceof Node\Stmt\Function_ || $node instanceof Node\Stmt\ClassMethod || $node instanceof Node\Expr\Closure) { array_pop($this->byRefStack); } @@ -283,6 +300,122 @@ public function leaveNode(Node $node): Node|array|null return null; } + /** + * @return list + */ + private function collectUnprovenClassConstantChecks(Node\Stmt\Class_ $node, string $className): array + { + $injectedStmts = []; + + foreach ($node->stmts as $stmt) { + if (! ($stmt instanceof Node\Stmt\ClassConst)) { + continue; + } + + $doc = $stmt->getDocComment(); + if ($doc === null || ! str_contains($doc->getText(), '@var')) { + continue; + } + + if (Config::isRespectIgnoreTagsEnabled() && str_contains($doc->getText(), '@typephp-ignore')) { + continue; + } + + $varTag = DocblockExtractor::extractVarTagFromDoc($doc->getText()); + if ($varTag === null) { + continue; + } + + $typeString = $varTag[0]; + + try { + [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); + $tokens = new TokenIterator($lexer->tokenize(DocblockNormalizer::normalize($typeString))); + $typeNode = $typeParser->parse($tokens); + + foreach ($stmt->consts as $const) { + if (Config::isEliminateStaticallyProvenChecksEnabled() && StaticTypeEvaluator::satisfies($const->value, $typeNode, $this->currentFile)) { + continue; + } + + $constName = $const->name->toString(); + $fullTarget = $className . '::' . $constName; + $classConstFetch = new Node\Expr\ClassConstFetch(new Node\Name\FullyQualified($className), $constName); + + $checkCall = NodeBuilder::createConstantCheckCall( + $fullTarget, + $classConstFetch, + $typeString, + $const->getStartLine() + ); + + $checkStmt = new Node\Stmt\Expression(NodeBuilder::createTernaryThrowExpr($checkCall, $const->getStartLine())); + $checkStmt->setAttribute('typephp_injected', true); + $injectedStmts[] = $checkStmt; + } + } catch (\Throwable) { + } + } + + return $injectedStmts; + } + + /** + * @return list + */ + private function collectUnprovenGlobalConstantChecks(Node\Stmt\Const_ $node): array + { + $doc = $node->getDocComment(); + if ($doc === null || ! str_contains($doc->getText(), '@var')) { + return []; + } + + if (Config::isRespectIgnoreTagsEnabled() && str_contains($doc->getText(), '@typephp-ignore')) { + return []; + } + + $varTag = DocblockExtractor::extractVarTagFromDoc($doc->getText()); + if ($varTag === null) { + return []; + } + + $typeString = $varTag[0]; + $injectedStmts = []; + + try { + [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); + $tokens = new TokenIterator($lexer->tokenize(DocblockNormalizer::normalize($typeString))); + $typeNode = $typeParser->parse($tokens); + + foreach ($node->consts as $const) { + if (Config::isEliminateStaticallyProvenChecksEnabled() && StaticTypeEvaluator::satisfies($const->value, $typeNode, $this->currentFile)) { + continue; + } + + $constName = $const->name->toString(); + $qualifiedConstName = $this->currentNamespace !== '' + ? $this->currentNamespace . '\\' . $constName + : $constName; + + $constFetch = new Node\Expr\ConstFetch(new Node\Name\FullyQualified($qualifiedConstName)); + + $checkCall = NodeBuilder::createConstantCheckCall( + $qualifiedConstName, + $constFetch, + $typeString, + $const->getStartLine() + ); + + $checkStmt = new Node\Stmt\Expression(NodeBuilder::createTernaryThrowExpr($checkCall, $const->getStartLine())); + $checkStmt->setAttribute('typephp_injected', true); + $injectedStmts[] = $checkStmt; + } + } catch (\Throwable) { + } + + return $injectedStmts; + } + private function createForeachBoundaryCheck(Node\Stmt\Foreach_ $node): ?Node\Stmt\Expression { $targetVarExpr = null; @@ -324,7 +457,7 @@ private function createForeachBoundaryCheck(Node\Stmt\Foreach_ $node): ?Node\Stm private static function isLoopBodyFreeOfOpaqueMutations(Node\Stmt\Foreach_ $node): bool { - $visitor = new class () extends NodeVisitorAbstract { + $visitor = new class() extends NodeVisitorAbstract { public bool $hasOpaqueCalls = false; public function enterNode(Node $n): ?int diff --git a/src/Internal/Ast/NodeBuilder.php b/src/Internal/Ast/NodeBuilder.php index 07a97974..0b10a68d 100644 --- a/src/Internal/Ast/NodeBuilder.php +++ b/src/Internal/Ast/NodeBuilder.php @@ -140,4 +140,22 @@ public static function createPropertyMemberAssignCheckCall( ] ); } + + public static function createConstantCheckCall( + string $constantName, + Node\Expr $valueExpr, + string $typeString, + int $line + ): Node\Expr\FuncCall { + return new Node\Expr\FuncCall( + new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkConstant'), + [ + new Node\Arg(new Node\Scalar\String_($constantName)), + new Node\Arg($valueExpr), + new Node\Arg(new Node\Scalar\String_($typeString)), + new Node\Arg(new Node\Scalar\MagicConst\File()), + new Node\Arg(new Node\Scalar\LNumber($line)), + ] + ); + } } diff --git a/src/Internal/Reporting/ViolationCollector.php b/src/Internal/Reporting/ViolationCollector.php index 007f9084..8dd6558e 100644 --- a/src/Internal/Reporting/ViolationCollector.php +++ b/src/Internal/Reporting/ViolationCollector.php @@ -55,7 +55,7 @@ public static function reset(): void /** * Handles a validation failure according to the configured on_violation mode ('throw', 'warn', 'report'). * - * @param 'parameter'|'return'|'property'|'variable'|'param-out'|'self-out'|'callback'|'yield'|'send' $kind + * @param 'parameter'|'return'|'property'|'variable'|'param-out'|'self-out'|'callback'|'yield'|'send'|'constant' $kind */ public static function handle( ErrorMessage $error, diff --git a/src/Internal/Reporting/ViolationRecord.php b/src/Internal/Reporting/ViolationRecord.php index 4ceb3a84..f6b63a02 100644 --- a/src/Internal/Reporting/ViolationRecord.php +++ b/src/Internal/Reporting/ViolationRecord.php @@ -12,7 +12,7 @@ final class ViolationRecord implements JsonSerializable { /** - * @param 'parameter'|'return'|'property'|'variable'|'param-out'|'self-out'|'callback'|'yield'|'send' $kind + * @param 'parameter'|'return'|'property'|'variable'|'param-out'|'self-out'|'callback'|'yield'|'send'|'constant' $kind */ public function __construct( public readonly string $file, @@ -26,8 +26,7 @@ public function __construct( public readonly int $count = 1, public readonly ?string $caller = null, public readonly ?string $declaredIn = null - ) { - } + ) {} /** * Computes a deterministic deduplication hash for this violation. diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index b0dc9c71..17d21f13 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -6,6 +6,7 @@ use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode; use PHPStan\PhpDocParser\Ast\Type\TypeNode; +use PHPStan\PhpDocParser\Parser\TokenIterator; use TypePHP\Internal\Ast\ScopeCleaner; use TypePHP\Internal\Checker\GeneratorChecker; use TypePHP\Internal\Checker\InlineChecker; @@ -16,10 +17,13 @@ use TypePHP\Internal\Checker\SelfOutChecker; use TypePHP\Internal\Diagnostic\ErrorFactory; use TypePHP\Internal\Diagnostic\ErrorMessage; +use TypePHP\Internal\Docblock\DocblockExtractor; +use TypePHP\Internal\Docblock\DocblockNormalizer; use TypePHP\Internal\Docblock\DocblockParser; use TypePHP\Internal\Generics\TemplateManager; use TypePHP\Internal\Reporting\ViolationCollector; use TypePHP\Internal\Resolver\CallerBoundaryResolver; +use TypePHP\Internal\Resolver\SpecialTypeResolver; use TypePHP\Internal\Util\Config; use TypePHP\Internal\Util\IgnoreManager; use TypePHP\Internal\Validator\TypeValidatorRegistry; @@ -67,6 +71,47 @@ public static function isEnabled(): bool return Config::isEnabled(); } + /** + * Validates class-level and global constants against declared @var contracts upon declaration/load. + */ + public static function checkConstant( + string $constantName, + mixed $value, + string $typeString, + string $file = '', + ?int $line = null + ): mixed { + if (! Config::isEnabled()) { + return $value; + } + + try { + $normalized = DocblockNormalizer::normalize($typeString); + [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); + $tokens = new TokenIterator($lexer->tokenize($normalized)); + $typeNode = $typeParser->parse($tokens); + + if ($file !== '') { + $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $file); + } + + $context = "Constant {$constantName}"; + + $err = self::getRegistry()->validate($value, $typeNode, $context); + if ($err !== null) { + if (IgnoreManager::isCallerIgnored()) { + return $value; + } + + return ViolationCollector::handle($err, 'constant', $value, $file, $line, $constantName); + } + } catch (\Throwable $e) { + // Silently ignore unexpected parsing errors + } + + return $value; + } + /** * Evaluates member/dimension mutation assignments on an object or static property * ($obj->prop[$key] = $val or Class::$prop[$key] = $val) atomically before writing. diff --git a/tests/Internal/Ast/NodeBuilderTest.php b/tests/Internal/Ast/NodeBuilderTest.php index 7bf0db1a..881f43c9 100644 --- a/tests/Internal/Ast/NodeBuilderTest.php +++ b/tests/Internal/Ast/NodeBuilderTest.php @@ -83,4 +83,20 @@ ->and($call->args)->toHaveCount(5) ; }); + + test('createConstantCheckCall creates FuncCall node for RuntimeTypeChecker::checkConstant', function () { + $valExpr = new Node\Expr\ClassConstFetch(new Node\Name\FullyQualified('App\Config'), 'Data'); + + $call = NodeBuilder::createConstantCheckCall('App\Config::Data', $valExpr, 'list', 12); + + expect($call)->toBeInstanceOf(Node\Expr\FuncCall::class) + ->and($call->name->toString())->toBe('TypePHP\Internal\RuntimeTypeChecker::checkConstant') + ->and($call->args)->toHaveCount(5) + ->and($call->args[0]->value->value)->toBe('App\Config::Data') + ->and($call->args[1]->value)->toBe($valExpr) + ->and($call->args[2]->value->value)->toBe('list') + ->and($call->args[3]->value)->toBeInstanceOf(Node\Scalar\MagicConst\File::class) + ->and($call->args[4]->value->value)->toBe(12) + ; + }); }); diff --git a/tests/Internal/RuntimeTypeCheckerTest.php b/tests/Internal/RuntimeTypeCheckerTest.php index 96517bcd..cb61ac6d 100644 --- a/tests/Internal/RuntimeTypeCheckerTest.php +++ b/tests/Internal/RuntimeTypeCheckerTest.php @@ -69,9 +69,7 @@ public static function run(callable $fn): mixed * * @param-out positive-int $id */ -function runtimeTestParamOutFixture(mixed &$id): void -{ -} +function runtimeTestParamOutFixture(mixed &$id): void {} /** * Self-contained fixture: self-out state transitions @@ -83,9 +81,7 @@ class RuntimeTestSessionFixture /** * @self-out self<'authenticated'> */ - public function login(): void - { - } + public function login(): void {} } /** @@ -101,9 +97,7 @@ function runtimeTestGeneratorFixture(): Generator /** * @param mixed $a */ -function runtimeUnconstrainedParams(mixed $a): void -{ -} +function runtimeUnconstrainedParams(mixed $a): void {} /** * @return mixed @@ -144,14 +138,14 @@ function runtimeUnconstrainedReturn(): mixed test('withPendingGeneric pushes and pops instantiation context', function () { $instantiated = RuntimeTypeChecker::withPendingGeneric( Container::class . '<' . Dog::class . '>', - fn () => new Container(new Dog()), + fn() => new Container(new Dog()), __FILE__ ); expect($instantiated)->toBeInstanceOf(Container::class); Config::set(['enabled' => false]); - $bypass = RuntimeTypeChecker::withPendingGeneric('any', fn () => 123); + $bypass = RuntimeTypeChecker::withPendingGeneric('any', fn() => 123); expect($bypass)->toBe(123); }); @@ -163,9 +157,8 @@ function runtimeUnconstrainedReturn(): mixed $cached = RuntimeTypeChecker::checkStaticProperty(StaticPropFixture::class, 'count', 10, __FILE__, 1); expect($cached)->toBe(10); - expect(fn () => RuntimeTypeChecker::checkStaticProperty(StaticPropFixture::class, 'badCount', -5, __FILE__, 1)) - ->toThrow(TypeError::class, 'positive-int') - ; + expect(fn() => RuntimeTypeChecker::checkStaticProperty(StaticPropFixture::class, 'badCount', -5, __FILE__, 1)) + ->toThrow(TypeError::class, 'positive-int'); Config::set(['enabled' => false]); expect(RuntimeTypeChecker::checkStaticProperty(StaticPropFixture::class, 'disabledCount', -50))->toBe(-50); @@ -355,7 +348,7 @@ function runtimeUnconstrainedReturn(): mixed }); test('wrapCallable and wrapIterable respect disabled switch', function () { - $cb = fn () => 1; + $cb = fn() => 1; expect(RuntimeTypeChecker::wrapCallable('nonExistent', 'arg', $cb))->toBe($cb); $iter = [1, 2, 3]; @@ -388,52 +381,52 @@ function runtimeUnconstrainedReturn(): mixed $badNode = new GenericTypeNode(new IdentifierTypeNode(Container::class), [new IdentifierTypeNode(Cat::class)]); $resNode = RuntimeCheckerIgnoredCaller::run( - fn () => RuntimeTypeChecker::bindInstanceFromNode($dog, $badNode) + fn() => RuntimeTypeChecker::bindInstanceFromNode($dog, $badNode) ); expect($resNode)->toBeNull(); $resVar = RuntimeCheckerIgnoredCaller::run( - fn () => RuntimeTypeChecker::checkVariable(-5, 'positive-int', 'val', __FILE__) + fn() => RuntimeTypeChecker::checkVariable(-5, 'positive-int', 'val', __FILE__) ); expect($resVar)->toBe(-5); $fixture = new ConfiguredProperty(); $resProp = RuntimeCheckerIgnoredCaller::run( - fn () => RuntimeTypeChecker::checkProperty(['bad'], $fixture, 'numbers', __FILE__) + fn() => RuntimeTypeChecker::checkProperty(['bad'], $fixture, 'numbers', __FILE__) ); expect($resProp)->toBe(['bad']); $resMember = RuntimeCheckerIgnoredCaller::run( - fn () => RuntimeTypeChecker::checkMemberAssign(['count' => 5], [['dim', 'count']], 'not_an_int', 'array{count: int}', 'stats', __FILE__) + fn() => RuntimeTypeChecker::checkMemberAssign(['count' => 5], [['dim', 'count']], 'not_an_int', 'array{count: int}', 'stats', __FILE__) ); expect($resMember)->toBe('not_an_int'); $resParams = RuntimeCheckerIgnoredCaller::run( - fn () => RuntimeTypeChecker::checkParams(UserService::class . '::find', ['id' => -1], new UserService()) + fn() => RuntimeTypeChecker::checkParams(UserService::class . '::find', ['id' => -1], new UserService()) ); expect($resParams)->toBeNull(); $resOut = RuntimeCheckerIgnoredCaller::run( - fn () => RuntimeTypeChecker::checkParamOut('runtimeTestParamOutFixture', 'id', -50) + fn() => RuntimeTypeChecker::checkParamOut('runtimeTestParamOutFixture', 'id', -50) ); expect($resOut)->toBeNull(); RuntimeCheckerIgnoredCaller::run( - fn () => RuntimeTypeChecker::checkSelfOut(RuntimeTestSessionFixture::class . '::login', new RuntimeTestSessionFixture()) + fn() => RuntimeTypeChecker::checkSelfOut(RuntimeTestSessionFixture::class . '::login', new RuntimeTestSessionFixture()) ); $resRet = RuntimeCheckerIgnoredCaller::run( - fn () => RuntimeTypeChecker::checkReturn(UserService::class . '::find', ['id' => -1, 'name' => 'Alice'], new UserService()) + fn() => RuntimeTypeChecker::checkReturn(UserService::class . '::find', ['id' => -1, 'name' => 'Alice'], new UserService()) ); expect($resRet)->toBe(['id' => -1, 'name' => 'Alice']); $resSend = RuntimeCheckerIgnoredCaller::run( - fn () => RuntimeTypeChecker::checkSend('runtimeTestGeneratorFixture', -50) + fn() => RuntimeTypeChecker::checkSend('runtimeTestGeneratorFixture', -50) ); expect($resSend)->toBe(-50); $resYield = RuntimeCheckerIgnoredCaller::run( - fn () => RuntimeTypeChecker::checkYield('runtimeTestGeneratorFixture', 123, -50) + fn() => RuntimeTypeChecker::checkYield('runtimeTestGeneratorFixture', 123, -50) ); expect($resYield)->toBe(-50); }); @@ -484,63 +477,63 @@ function vendorAction(): void $badNode = new GenericTypeNode(new IdentifierTypeNode(Container::class), [new IdentifierTypeNode(Cat::class)]); $resNode = Acme\VendorTest\VendorCaller::call( - fn () => RuntimeTypeChecker::bindInstanceFromNode($dog, $badNode, $fnName) + fn() => RuntimeTypeChecker::bindInstanceFromNode($dog, $badNode, $fnName) ); expect($resNode)->toBeNull(); $resVar = Acme\VendorTest\VendorCaller::call( - fn () => RuntimeTypeChecker::checkVariable(-5, 'positive-int', 'v', __FILE__, $fnName) + fn() => RuntimeTypeChecker::checkVariable(-5, 'positive-int', 'v', __FILE__, $fnName) ); expect($resVar)->toBe(-5); $resProp = Acme\VendorTest\VendorCaller::call( - fn () => RuntimeTypeChecker::checkProperty(['bad'], 'Acme\VendorTest\VendorCaller', 'prop', __FILE__) + fn() => RuntimeTypeChecker::checkProperty(['bad'], 'Acme\VendorTest\VendorCaller', 'prop', __FILE__) ); expect($resProp)->toBe(['bad']); $resMember = Acme\VendorTest\VendorCaller::call( - fn () => RuntimeTypeChecker::checkMemberAssign(['count' => 5], [['dim', 'count']], 'not_an_int', 'array{count: int}', 'stats', __FILE__, $fnName) + fn() => RuntimeTypeChecker::checkMemberAssign(['count' => 5], [['dim', 'count']], 'not_an_int', 'array{count: int}', 'stats', __FILE__, $fnName) ); expect($resMember)->toBe('not_an_int'); $resParams = Acme\VendorTest\VendorCaller::call( - fn () => RuntimeTypeChecker::checkParams($fnName, ['a' => 1]) + fn() => RuntimeTypeChecker::checkParams($fnName, ['a' => 1]) ); expect($resParams)->toBeNull(); $resOut = Acme\VendorTest\VendorCaller::call( - fn () => RuntimeTypeChecker::checkParamOut($fnName, 'param', 1) + fn() => RuntimeTypeChecker::checkParamOut($fnName, 'param', 1) ); expect($resOut)->toBeNull(); Acme\VendorTest\VendorCaller::call( - fn () => RuntimeTypeChecker::checkSelfOut($fnName, new stdClass()) + fn() => RuntimeTypeChecker::checkSelfOut($fnName, new stdClass()) ); $resRet = Acme\VendorTest\VendorCaller::call( - fn () => RuntimeTypeChecker::checkReturn($fnName, 'any') + fn() => RuntimeTypeChecker::checkReturn($fnName, 'any') ); expect($resRet)->toBe('any'); $resSend = Acme\VendorTest\VendorCaller::call( - fn () => RuntimeTypeChecker::checkSend($fnName, 'val') + fn() => RuntimeTypeChecker::checkSend($fnName, 'val') ); expect($resSend)->toBe('val'); $resYield = Acme\VendorTest\VendorCaller::call( - fn () => RuntimeTypeChecker::checkYield($fnName, 'k', 'v') + fn() => RuntimeTypeChecker::checkYield($fnName, 'k', 'v') ); expect($resYield)->toBe('v'); - $cb = fn () => 1; + $cb = fn() => 1; $resCb = Acme\VendorTest\VendorCaller::call( - fn () => RuntimeTypeChecker::wrapCallable($fnName, 'cb', $cb) + fn() => RuntimeTypeChecker::wrapCallable($fnName, 'cb', $cb) ); expect($resCb)->toBe($cb); $iter = [1]; $resIter = Acme\VendorTest\VendorCaller::call( - fn () => RuntimeTypeChecker::wrapIterable($fnName, 'iter', $iter) + fn() => RuntimeTypeChecker::wrapIterable($fnName, 'iter', $iter) ); expect($resIter)->toBe($iter); } finally { @@ -743,23 +736,47 @@ function vendorAction(): void ; $ignored = RuntimeCheckerIgnoredCaller::run( - fn () => RuntimeTypeChecker::checkPropertyMemberAssign($fixture, 'numbers', [['dim', null]], 'wrong', __FILE__) + fn() => RuntimeTypeChecker::checkPropertyMemberAssign($fixture, 'numbers', [['dim', null]], 'wrong', __FILE__) ); expect($ignored)->toBe('wrong'); Config::set(['enabled' => false]); expect(RuntimeTypeChecker::checkPropertyMemberAssign($fixture, 'numbers', [['dim', null]], 'wrong', __FILE__)) - ->toBe('wrong') - ; + ->toBe('wrong'); }); test('checkStaticProperty does not mark property as checked when validation fails and throws', function () { - expect(fn () => RuntimeTypeChecker::checkStaticProperty(StaticPropFixture::class, 'badCount', -5, __FILE__, 1)) - ->toThrow(TypeError::class, 'positive-int') + expect(fn() => RuntimeTypeChecker::checkStaticProperty(StaticPropFixture::class, 'badCount', -5, __FILE__, 1)) + ->toThrow(TypeError::class, 'positive-int'); + + expect(fn() => RuntimeTypeChecker::checkStaticProperty(StaticPropFixture::class, 'badCount', -5, __FILE__, 1)) + ->toThrow(TypeError::class, 'positive-int'); + }); + + test('checkConstant validates class and global constants and respects disabled switch', function () { + $valid = RuntimeTypeChecker::checkConstant('App\Config::Data', ['User', 'Product'], 'list', __FILE__, 10); + expect($valid)->toBe(['User', 'Product']); + + $invalidClass = RuntimeTypeChecker::checkConstant('App\Config::Data', ['user' => 'User'], 'list', __FILE__, 10); + expect($invalidClass)->toBeInstanceOf(ErrorMessage::class) + ->and($invalidClass->getMessage())->toContain('must be a list') ; - expect(fn () => RuntimeTypeChecker::checkStaticProperty(StaticPropFixture::class, 'badCount', -5, __FILE__, 1)) - ->toThrow(TypeError::class, 'positive-int') + $invalidGlobal = RuntimeTypeChecker::checkConstant('GLOBAL_TIMEOUT', -5, 'positive-int', __FILE__, 20); + expect($invalidGlobal)->toBeInstanceOf(ErrorMessage::class) + ->and($invalidGlobal->getMessage())->toContain('must be of type positive-int') ; + + Config::set(['enabled' => false]); + expect(RuntimeTypeChecker::checkConstant('App\Config::Data', ['user' => 'User'], 'list', __FILE__, 10)) + ->toBe(['user' => 'User']); + }); + + test('checkConstant respects @typephp-ignore on caller', function () { + $res = RuntimeCheckerIgnoredCaller::run( + fn() => RuntimeTypeChecker::checkConstant('App\Config::Data', ['user' => 'User'], 'list', __FILE__, 10) + ); + + expect($res)->toBe(['user' => 'User']); }); }); diff --git a/tests/TypeChecking/Boundaries/ConstantContractsTest.php b/tests/TypeChecking/Boundaries/ConstantContractsTest.php new file mode 100644 index 00000000..138faaed --- /dev/null +++ b/tests/TypeChecking/Boundaries/ConstantContractsTest.php @@ -0,0 +1,287 @@ + contract (User Reproduction)', function () { + $source = <<<'PHP' + + */ + public const array Data = [ + 'user' => 'User', + 'product' => 'Product', + ]; +} +PHP; + + $tempDir = sys_get_temp_dir() . '/typephp_const_' . uniqid(); + mkdir($tempDir, 0777, true); + $filePath = $tempDir . '/FixtureBadListConst.php'; + file_put_contents($filePath, $source); + + try { + StreamWrapper::register(); + + expect(fn () => require $filePath) + ->toThrow(TypeError::class, 'Constant TypePHP\Tests\TypeChecking\Boundaries\FixtureBadListConst::Data must be a list, associative array (key \'user\') given') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('accepts class constant satisfying list contract', function () { + $source = <<<'PHP' + + */ + public const array Data = [ + 'User', + 'Product', + ]; +} + +return FixtureValidListConst::Data; +PHP; + + $tempDir = sys_get_temp_dir() . '/typephp_const_' . uniqid(); + mkdir($tempDir, 0777, true); + $filePath = $tempDir . '/FixtureValidListConst.php'; + file_put_contents($filePath, $source); + + try { + StreamWrapper::register(); + + $result = require $filePath; + expect($result)->toBe(['User', 'Product']); + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('throws TypeError when class constant violates scalar refinement (positive-int)', function () { + $source = <<<'PHP' + require $filePath) + ->toThrow(TypeError::class, 'Constant TypePHP\Tests\TypeChecking\Boundaries\FixtureBadScalarConst::RETRIES must be of type positive-int, negative int (-5) given') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('throws TypeError when class constant violates array shape', function () { + $source = <<<'PHP' + -1, + 'role' => 'admin', + ]; +} +PHP; + + $tempDir = sys_get_temp_dir() . '/typephp_const_' . uniqid(); + mkdir($tempDir, 0777, true); + $filePath = $tempDir . '/FixtureBadShapeConst.php'; + file_put_contents($filePath, $source); + + try { + StreamWrapper::register(); + + expect(fn () => require $filePath) + ->toThrow(TypeError::class, "['id'] must be of type positive-int") + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + }); + + describe('2. Global Constant Validation', function () { + test('throws TypeError when global const violates non-empty-string contract', function () { + $source = <<<'PHP' + require $filePath) + ->toThrow(TypeError::class, 'Constant GLOBAL_BAD_EMPTY_NAME must be of type non-empty-string') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + }); + + describe('3. Compile-Time Static Elimination & Zero Line-Drift', function () { + test('eliminates check on statically proven valid constant (zero injections)', function () { + $source = <<<'PHP' + + */ + public const Data = ['User', 'Product']; +} +PHP; + + $transformed = StreamWrapper::transformSource($source, 'ValidConfig.php'); + + expect($transformed)->not()->toContain('RuntimeTypeChecker::checkConstant') + ->and($transformed)->not()->toContain('checkClassConstant') + ; + }); + + test('guarantees zero line-drift when constant check is injected', function () { + $source = <<<'PHP' + + */ + public const array Data = [ + 'user' => 'User', + ]; +} + +$landmark = 'line_16_exact'; +PHP; + + $transformed = StreamWrapper::transformSource($source, 'ConfigWithDriftCheck.php'); + + $origLines = explode("\n", str_replace("\r\n", "\n", $source)); + $transLines = explode("\n", str_replace("\r\n", "\n", $transformed)); + + expect(\count($transLines))->toBe(\count($origLines)); + + $origIndex = array_search('$landmark = \'line_16_exact\';', array_map('trim', $origLines), true); + $transIndex = array_search('$landmark = \'line_16_exact\';', array_map('trim', $transLines), true); + + expect($transIndex)->toBe($origIndex) + ->and($origIndex)->toBe(16) + ; + }); + + test('points to exact line number of the constant definition in thrown TypeError', function () { + $source = <<<'PHP' +getLine())->toBe(12); + } + + expect($caught)->toBeTrue(); + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + }); +}); \ No newline at end of file From d765f734528ea4d4c33c61ec66cfd8d07463cb18 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Mon, 9 Nov 2026 01:11:39 +0800 Subject: [PATCH 09/11] Enhance constant closure handling by adding validation for parameters and return types, including new checks and tests for contract compliance --- src/Internal/Ast/ContractVisitor.php | 145 ++++++++- src/Internal/Ast/NodeBuilder.php | 38 +++ src/Internal/Reporting/ViolationRecord.php | 3 +- src/Internal/RuntimeTypeChecker.php | 81 +++++ tests/Internal/RuntimeTypeCheckerTest.php | 89 +++--- .../Boundaries/ConstantContractsTest.php | 279 +++++++++++++++++- 6 files changed, 587 insertions(+), 48 deletions(-) diff --git a/src/Internal/Ast/ContractVisitor.php b/src/Internal/Ast/ContractVisitor.php index eeb8b687..bc75fb6a 100644 --- a/src/Internal/Ast/ContractVisitor.php +++ b/src/Internal/Ast/ContractVisitor.php @@ -10,7 +10,9 @@ use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode; use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode; +use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode; use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode; +use PHPStan\PhpDocParser\Ast\Type\TypeNode; use PHPStan\PhpDocParser\Parser\TokenIterator; use TypePHP\Internal\Ast\Elimination\StaticTypeEvaluator; use TypePHP\Internal\Docblock\DocblockExtractor; @@ -334,12 +336,19 @@ private function collectUnprovenClassConstantChecks(Node\Stmt\Class_ $node, stri $typeNode = $typeParser->parse($tokens); foreach ($stmt->consts as $const) { + $constName = $const->name->toString(); + $fullTarget = $className . '::' . $constName; + + if ($const->value instanceof Node\Expr\Closure && $typeNode instanceof CallableTypeNode) { + $this->instrumentConstantClosure($const->value, $typeNode, $fullTarget); + + continue; + } + if (Config::isEliminateStaticallyProvenChecksEnabled() && StaticTypeEvaluator::satisfies($const->value, $typeNode, $this->currentFile)) { continue; } - $constName = $const->name->toString(); - $fullTarget = $className . '::' . $constName; $classConstFetch = new Node\Expr\ClassConstFetch(new Node\Name\FullyQualified($className), $constName); $checkCall = NodeBuilder::createConstantCheckCall( @@ -388,15 +397,21 @@ private function collectUnprovenGlobalConstantChecks(Node\Stmt\Const_ $node): ar $typeNode = $typeParser->parse($tokens); foreach ($node->consts as $const) { - if (Config::isEliminateStaticallyProvenChecksEnabled() && StaticTypeEvaluator::satisfies($const->value, $typeNode, $this->currentFile)) { - continue; - } - $constName = $const->name->toString(); $qualifiedConstName = $this->currentNamespace !== '' ? $this->currentNamespace . '\\' . $constName : $constName; + if ($const->value instanceof Node\Expr\Closure && $typeNode instanceof CallableTypeNode) { + $this->instrumentConstantClosure($const->value, $typeNode, $qualifiedConstName); + + continue; + } + + if (Config::isEliminateStaticallyProvenChecksEnabled() && StaticTypeEvaluator::satisfies($const->value, $typeNode, $this->currentFile)) { + continue; + } + $constFetch = new Node\Expr\ConstFetch(new Node\Name\FullyQualified($qualifiedConstName)); $checkCall = NodeBuilder::createConstantCheckCall( @@ -416,6 +431,122 @@ private function collectUnprovenGlobalConstantChecks(Node\Stmt\Const_ $node): ar return $injectedStmts; } + private function instrumentConstantClosure( + Node\Expr\Closure $closure, + CallableTypeNode $callableTypeNode, + string $caller + ): void { + $paramChecks = []; + $callableParams = $callableTypeNode->parameters; + $paramsByName = []; + + foreach ($callableParams as $idx => $pNode) { + $pName = $pNode->parameterName !== null ? ltrim($pNode->parameterName, '$') : null; + if ($pName !== null) { + $paramsByName[$pName] = $pNode; + } elseif (isset($closure->params[$idx])) { + $closureParam = $closure->params[$idx]; + if ($closureParam->var instanceof Node\Expr\Variable && \is_string($closureParam->var->name)) { + $paramsByName[$closureParam->var->name] = $pNode; + } + } + } + + foreach ($closure->params as $param) { + if ($param->var instanceof Node\Expr\Variable && \is_string($param->var->name)) { + $pName = $param->var->name; + $pContract = $paramsByName[$pName] ?? null; + + if ($pContract !== null) { + $typeStr = (string) $pContract->type; + if (strtolower(trim($typeStr)) === 'mixed') { + continue; + } + + $line = $param->getStartLine(); + $checkCall = NodeBuilder::createConstantClosureParamCheckCall( + $caller, + $pName, + new Node\Expr\Variable($pName), + $typeStr, + $line + ); + $checkStmt = new Node\Stmt\Expression(NodeBuilder::createTernaryThrowExpr($checkCall, $line)); + $checkStmt->setAttribute('typephp_injected', true); + $paramChecks[] = $checkStmt; + } + } + } + + if ($paramChecks !== []) { + $closure->stmts = [...$paramChecks, ...$closure->stmts]; + } + + $returnTypeNode = $callableTypeNode->returnType; + $returnTypeStr = (string) $returnTypeNode; + $isReturnUnconstrained = \in_array(strtolower(trim($returnTypeStr)), ['void', 'mixed'], true); + + if (! $isReturnUnconstrained) { + $traverser = new NodeTraverser(); + $traverser->addVisitor(new class ( + $caller, + $returnTypeNode, + $returnTypeStr, + $this->currentFile + ) extends NodeVisitorAbstract { + public function __construct( + private string $caller, + private TypeNode $returnTypeNode, + private string $returnTypeStr, + private string $currentFile + ) { + } + + public function enterNode(Node $n): int|Node|null + { + if ( + $n instanceof Node\Expr\Closure + || $n instanceof Node\Expr\ArrowFunction + || $n instanceof Node\Stmt\Function_ + || $n instanceof Node\Stmt\ClassMethod + || $n instanceof Node\Stmt\Class_ + ) { + return NodeTraverser::DONT_TRAVERSE_CHILDREN; + } + + if ($n instanceof Node\Stmt\Return_) { + $exprToWrap = $n->expr ?? new Node\Expr\ConstFetch(new Node\Name('null')); + + if ( + Config::isEliminateStaticallyProvenChecksEnabled() + && StaticTypeEvaluator::satisfies($exprToWrap, $this->returnTypeNode, $this->currentFile) + ) { + return null; + } + + $line = $n->getStartLine(); + $checkCall = NodeBuilder::createConstantClosureReturnCheckCall( + $this->caller, + $exprToWrap, + $this->returnTypeStr, + $line + ); + + $n->expr = FunctionContractInjector::buildTernaryReturnExpr($checkCall, $line); + + return $n; + } + + return null; + } + }); + + /** @var array $newStmts */ + $newStmts = $traverser->traverse($closure->stmts); + $closure->stmts = $newStmts; + } + } + private function createForeachBoundaryCheck(Node\Stmt\Foreach_ $node): ?Node\Stmt\Expression { $targetVarExpr = null; @@ -457,7 +588,7 @@ private function createForeachBoundaryCheck(Node\Stmt\Foreach_ $node): ?Node\Stm private static function isLoopBodyFreeOfOpaqueMutations(Node\Stmt\Foreach_ $node): bool { - $visitor = new class() extends NodeVisitorAbstract { + $visitor = new class () extends NodeVisitorAbstract { public bool $hasOpaqueCalls = false; public function enterNode(Node $n): ?int diff --git a/src/Internal/Ast/NodeBuilder.php b/src/Internal/Ast/NodeBuilder.php index 0b10a68d..10a4ba00 100644 --- a/src/Internal/Ast/NodeBuilder.php +++ b/src/Internal/Ast/NodeBuilder.php @@ -158,4 +158,42 @@ public static function createConstantCheckCall( ] ); } + + public static function createConstantClosureParamCheckCall( + string $caller, + string $paramName, + Node\Expr $paramVar, + string $typeString, + int $line + ): Node\Expr\FuncCall { + return new Node\Expr\FuncCall( + new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkConstantClosureParam'), + [ + new Node\Arg(new Node\Scalar\String_($caller)), + new Node\Arg(new Node\Scalar\String_($paramName)), + new Node\Arg($paramVar), + new Node\Arg(new Node\Scalar\String_($typeString)), + new Node\Arg(new Node\Scalar\MagicConst\File()), + new Node\Arg(new Node\Scalar\LNumber($line)), + ] + ); + } + + public static function createConstantClosureReturnCheckCall( + string $caller, + Node\Expr $valueExpr, + string $typeString, + int $line + ): Node\Expr\FuncCall { + return new Node\Expr\FuncCall( + new Node\Name\FullyQualified('TypePHP\Internal\RuntimeTypeChecker::checkConstantClosureReturn'), + [ + new Node\Arg(new Node\Scalar\String_($caller)), + new Node\Arg($valueExpr), + new Node\Arg(new Node\Scalar\String_($typeString)), + new Node\Arg(new Node\Scalar\MagicConst\File()), + new Node\Arg(new Node\Scalar\LNumber($line)), + ] + ); + } } diff --git a/src/Internal/Reporting/ViolationRecord.php b/src/Internal/Reporting/ViolationRecord.php index f6b63a02..4993f24a 100644 --- a/src/Internal/Reporting/ViolationRecord.php +++ b/src/Internal/Reporting/ViolationRecord.php @@ -26,7 +26,8 @@ public function __construct( public readonly int $count = 1, public readonly ?string $caller = null, public readonly ?string $declaredIn = null - ) {} + ) { + } /** * Computes a deterministic deduplication hash for this violation. diff --git a/src/Internal/RuntimeTypeChecker.php b/src/Internal/RuntimeTypeChecker.php index 17d21f13..558aa52e 100644 --- a/src/Internal/RuntimeTypeChecker.php +++ b/src/Internal/RuntimeTypeChecker.php @@ -112,6 +112,87 @@ public static function checkConstant( return $value; } + /** + * Validates an argument passed into a constant closure against its parameter contract. + */ + public static function checkConstantClosureParam( + string $caller, + string $paramName, + mixed $value, + string $typeString, + string $file = '', + ?int $line = null + ): mixed { + if (! Config::isEnabled() || ! Config::isParamsEnabled()) { + return $value; + } + + try { + $normalized = DocblockNormalizer::normalize($typeString); + [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); + $tokens = new TokenIterator($lexer->tokenize($normalized)); + $typeNode = $typeParser->parse($tokens); + + if ($file !== '') { + $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $file); + } + + $context = "{$caller}(): Argument \${$paramName}"; + + $err = self::getRegistry()->validate($value, $typeNode, $context); + if ($err !== null) { + if (IgnoreManager::isCallerIgnored()) { + return $value; + } + + return ViolationCollector::handle($err, 'parameter', $value, $file, $line, $caller, '$' . $paramName); + } + } catch (\Throwable $e) { + } + + return $value; + } + + /** + * Validates a return value from a constant closure against its return type contract. + */ + public static function checkConstantClosureReturn( + string $caller, + mixed $value, + string $typeString, + string $file = '', + ?int $line = null + ): mixed { + if (! Config::isEnabled() || ! Config::isReturnsEnabled()) { + return $value; + } + + try { + $normalized = DocblockNormalizer::normalize($typeString); + [$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents(); + $tokens = new TokenIterator($lexer->tokenize($normalized)); + $typeNode = $typeParser->parse($tokens); + + if ($file !== '') { + $typeNode = SpecialTypeResolver::resolveForFile($typeNode, $file); + } + + $context = "{$caller}(): Return value"; + + $err = self::getRegistry()->validate($value, $typeNode, $context); + if ($err !== null) { + if (IgnoreManager::isCallerIgnored()) { + return $value; + } + + return ViolationCollector::handle($err, 'return', $value, $file, $line, $caller, 'return'); + } + } catch (\Throwable $e) { + } + + return $value; + } + /** * Evaluates member/dimension mutation assignments on an object or static property * ($obj->prop[$key] = $val or Class::$prop[$key] = $val) atomically before writing. diff --git a/tests/Internal/RuntimeTypeCheckerTest.php b/tests/Internal/RuntimeTypeCheckerTest.php index cb61ac6d..c2f21d6f 100644 --- a/tests/Internal/RuntimeTypeCheckerTest.php +++ b/tests/Internal/RuntimeTypeCheckerTest.php @@ -69,7 +69,9 @@ public static function run(callable $fn): mixed * * @param-out positive-int $id */ -function runtimeTestParamOutFixture(mixed &$id): void {} +function runtimeTestParamOutFixture(mixed &$id): void +{ +} /** * Self-contained fixture: self-out state transitions @@ -81,7 +83,9 @@ class RuntimeTestSessionFixture /** * @self-out self<'authenticated'> */ - public function login(): void {} + public function login(): void + { + } } /** @@ -97,7 +101,9 @@ function runtimeTestGeneratorFixture(): Generator /** * @param mixed $a */ -function runtimeUnconstrainedParams(mixed $a): void {} +function runtimeUnconstrainedParams(mixed $a): void +{ +} /** * @return mixed @@ -138,14 +144,14 @@ function runtimeUnconstrainedReturn(): mixed test('withPendingGeneric pushes and pops instantiation context', function () { $instantiated = RuntimeTypeChecker::withPendingGeneric( Container::class . '<' . Dog::class . '>', - fn() => new Container(new Dog()), + fn () => new Container(new Dog()), __FILE__ ); expect($instantiated)->toBeInstanceOf(Container::class); Config::set(['enabled' => false]); - $bypass = RuntimeTypeChecker::withPendingGeneric('any', fn() => 123); + $bypass = RuntimeTypeChecker::withPendingGeneric('any', fn () => 123); expect($bypass)->toBe(123); }); @@ -157,8 +163,9 @@ function runtimeUnconstrainedReturn(): mixed $cached = RuntimeTypeChecker::checkStaticProperty(StaticPropFixture::class, 'count', 10, __FILE__, 1); expect($cached)->toBe(10); - expect(fn() => RuntimeTypeChecker::checkStaticProperty(StaticPropFixture::class, 'badCount', -5, __FILE__, 1)) - ->toThrow(TypeError::class, 'positive-int'); + expect(fn () => RuntimeTypeChecker::checkStaticProperty(StaticPropFixture::class, 'badCount', -5, __FILE__, 1)) + ->toThrow(TypeError::class, 'positive-int') + ; Config::set(['enabled' => false]); expect(RuntimeTypeChecker::checkStaticProperty(StaticPropFixture::class, 'disabledCount', -50))->toBe(-50); @@ -348,7 +355,7 @@ function runtimeUnconstrainedReturn(): mixed }); test('wrapCallable and wrapIterable respect disabled switch', function () { - $cb = fn() => 1; + $cb = fn () => 1; expect(RuntimeTypeChecker::wrapCallable('nonExistent', 'arg', $cb))->toBe($cb); $iter = [1, 2, 3]; @@ -381,52 +388,52 @@ function runtimeUnconstrainedReturn(): mixed $badNode = new GenericTypeNode(new IdentifierTypeNode(Container::class), [new IdentifierTypeNode(Cat::class)]); $resNode = RuntimeCheckerIgnoredCaller::run( - fn() => RuntimeTypeChecker::bindInstanceFromNode($dog, $badNode) + fn () => RuntimeTypeChecker::bindInstanceFromNode($dog, $badNode) ); expect($resNode)->toBeNull(); $resVar = RuntimeCheckerIgnoredCaller::run( - fn() => RuntimeTypeChecker::checkVariable(-5, 'positive-int', 'val', __FILE__) + fn () => RuntimeTypeChecker::checkVariable(-5, 'positive-int', 'val', __FILE__) ); expect($resVar)->toBe(-5); $fixture = new ConfiguredProperty(); $resProp = RuntimeCheckerIgnoredCaller::run( - fn() => RuntimeTypeChecker::checkProperty(['bad'], $fixture, 'numbers', __FILE__) + fn () => RuntimeTypeChecker::checkProperty(['bad'], $fixture, 'numbers', __FILE__) ); expect($resProp)->toBe(['bad']); $resMember = RuntimeCheckerIgnoredCaller::run( - fn() => RuntimeTypeChecker::checkMemberAssign(['count' => 5], [['dim', 'count']], 'not_an_int', 'array{count: int}', 'stats', __FILE__) + fn () => RuntimeTypeChecker::checkMemberAssign(['count' => 5], [['dim', 'count']], 'not_an_int', 'array{count: int}', 'stats', __FILE__) ); expect($resMember)->toBe('not_an_int'); $resParams = RuntimeCheckerIgnoredCaller::run( - fn() => RuntimeTypeChecker::checkParams(UserService::class . '::find', ['id' => -1], new UserService()) + fn () => RuntimeTypeChecker::checkParams(UserService::class . '::find', ['id' => -1], new UserService()) ); expect($resParams)->toBeNull(); $resOut = RuntimeCheckerIgnoredCaller::run( - fn() => RuntimeTypeChecker::checkParamOut('runtimeTestParamOutFixture', 'id', -50) + fn () => RuntimeTypeChecker::checkParamOut('runtimeTestParamOutFixture', 'id', -50) ); expect($resOut)->toBeNull(); RuntimeCheckerIgnoredCaller::run( - fn() => RuntimeTypeChecker::checkSelfOut(RuntimeTestSessionFixture::class . '::login', new RuntimeTestSessionFixture()) + fn () => RuntimeTypeChecker::checkSelfOut(RuntimeTestSessionFixture::class . '::login', new RuntimeTestSessionFixture()) ); $resRet = RuntimeCheckerIgnoredCaller::run( - fn() => RuntimeTypeChecker::checkReturn(UserService::class . '::find', ['id' => -1, 'name' => 'Alice'], new UserService()) + fn () => RuntimeTypeChecker::checkReturn(UserService::class . '::find', ['id' => -1, 'name' => 'Alice'], new UserService()) ); expect($resRet)->toBe(['id' => -1, 'name' => 'Alice']); $resSend = RuntimeCheckerIgnoredCaller::run( - fn() => RuntimeTypeChecker::checkSend('runtimeTestGeneratorFixture', -50) + fn () => RuntimeTypeChecker::checkSend('runtimeTestGeneratorFixture', -50) ); expect($resSend)->toBe(-50); $resYield = RuntimeCheckerIgnoredCaller::run( - fn() => RuntimeTypeChecker::checkYield('runtimeTestGeneratorFixture', 123, -50) + fn () => RuntimeTypeChecker::checkYield('runtimeTestGeneratorFixture', 123, -50) ); expect($resYield)->toBe(-50); }); @@ -477,63 +484,63 @@ function vendorAction(): void $badNode = new GenericTypeNode(new IdentifierTypeNode(Container::class), [new IdentifierTypeNode(Cat::class)]); $resNode = Acme\VendorTest\VendorCaller::call( - fn() => RuntimeTypeChecker::bindInstanceFromNode($dog, $badNode, $fnName) + fn () => RuntimeTypeChecker::bindInstanceFromNode($dog, $badNode, $fnName) ); expect($resNode)->toBeNull(); $resVar = Acme\VendorTest\VendorCaller::call( - fn() => RuntimeTypeChecker::checkVariable(-5, 'positive-int', 'v', __FILE__, $fnName) + fn () => RuntimeTypeChecker::checkVariable(-5, 'positive-int', 'v', __FILE__, $fnName) ); expect($resVar)->toBe(-5); $resProp = Acme\VendorTest\VendorCaller::call( - fn() => RuntimeTypeChecker::checkProperty(['bad'], 'Acme\VendorTest\VendorCaller', 'prop', __FILE__) + fn () => RuntimeTypeChecker::checkProperty(['bad'], 'Acme\VendorTest\VendorCaller', 'prop', __FILE__) ); expect($resProp)->toBe(['bad']); $resMember = Acme\VendorTest\VendorCaller::call( - fn() => RuntimeTypeChecker::checkMemberAssign(['count' => 5], [['dim', 'count']], 'not_an_int', 'array{count: int}', 'stats', __FILE__, $fnName) + fn () => RuntimeTypeChecker::checkMemberAssign(['count' => 5], [['dim', 'count']], 'not_an_int', 'array{count: int}', 'stats', __FILE__, $fnName) ); expect($resMember)->toBe('not_an_int'); $resParams = Acme\VendorTest\VendorCaller::call( - fn() => RuntimeTypeChecker::checkParams($fnName, ['a' => 1]) + fn () => RuntimeTypeChecker::checkParams($fnName, ['a' => 1]) ); expect($resParams)->toBeNull(); $resOut = Acme\VendorTest\VendorCaller::call( - fn() => RuntimeTypeChecker::checkParamOut($fnName, 'param', 1) + fn () => RuntimeTypeChecker::checkParamOut($fnName, 'param', 1) ); expect($resOut)->toBeNull(); Acme\VendorTest\VendorCaller::call( - fn() => RuntimeTypeChecker::checkSelfOut($fnName, new stdClass()) + fn () => RuntimeTypeChecker::checkSelfOut($fnName, new stdClass()) ); $resRet = Acme\VendorTest\VendorCaller::call( - fn() => RuntimeTypeChecker::checkReturn($fnName, 'any') + fn () => RuntimeTypeChecker::checkReturn($fnName, 'any') ); expect($resRet)->toBe('any'); $resSend = Acme\VendorTest\VendorCaller::call( - fn() => RuntimeTypeChecker::checkSend($fnName, 'val') + fn () => RuntimeTypeChecker::checkSend($fnName, 'val') ); expect($resSend)->toBe('val'); $resYield = Acme\VendorTest\VendorCaller::call( - fn() => RuntimeTypeChecker::checkYield($fnName, 'k', 'v') + fn () => RuntimeTypeChecker::checkYield($fnName, 'k', 'v') ); expect($resYield)->toBe('v'); - $cb = fn() => 1; + $cb = fn () => 1; $resCb = Acme\VendorTest\VendorCaller::call( - fn() => RuntimeTypeChecker::wrapCallable($fnName, 'cb', $cb) + fn () => RuntimeTypeChecker::wrapCallable($fnName, 'cb', $cb) ); expect($resCb)->toBe($cb); $iter = [1]; $resIter = Acme\VendorTest\VendorCaller::call( - fn() => RuntimeTypeChecker::wrapIterable($fnName, 'iter', $iter) + fn () => RuntimeTypeChecker::wrapIterable($fnName, 'iter', $iter) ); expect($resIter)->toBe($iter); } finally { @@ -736,21 +743,24 @@ function vendorAction(): void ; $ignored = RuntimeCheckerIgnoredCaller::run( - fn() => RuntimeTypeChecker::checkPropertyMemberAssign($fixture, 'numbers', [['dim', null]], 'wrong', __FILE__) + fn () => RuntimeTypeChecker::checkPropertyMemberAssign($fixture, 'numbers', [['dim', null]], 'wrong', __FILE__) ); expect($ignored)->toBe('wrong'); Config::set(['enabled' => false]); expect(RuntimeTypeChecker::checkPropertyMemberAssign($fixture, 'numbers', [['dim', null]], 'wrong', __FILE__)) - ->toBe('wrong'); + ->toBe('wrong') + ; }); test('checkStaticProperty does not mark property as checked when validation fails and throws', function () { - expect(fn() => RuntimeTypeChecker::checkStaticProperty(StaticPropFixture::class, 'badCount', -5, __FILE__, 1)) - ->toThrow(TypeError::class, 'positive-int'); + expect(fn () => RuntimeTypeChecker::checkStaticProperty(StaticPropFixture::class, 'badCount', -5, __FILE__, 1)) + ->toThrow(TypeError::class, 'positive-int') + ; - expect(fn() => RuntimeTypeChecker::checkStaticProperty(StaticPropFixture::class, 'badCount', -5, __FILE__, 1)) - ->toThrow(TypeError::class, 'positive-int'); + expect(fn () => RuntimeTypeChecker::checkStaticProperty(StaticPropFixture::class, 'badCount', -5, __FILE__, 1)) + ->toThrow(TypeError::class, 'positive-int') + ; }); test('checkConstant validates class and global constants and respects disabled switch', function () { @@ -769,12 +779,13 @@ function vendorAction(): void Config::set(['enabled' => false]); expect(RuntimeTypeChecker::checkConstant('App\Config::Data', ['user' => 'User'], 'list', __FILE__, 10)) - ->toBe(['user' => 'User']); + ->toBe(['user' => 'User']) + ; }); test('checkConstant respects @typephp-ignore on caller', function () { $res = RuntimeCheckerIgnoredCaller::run( - fn() => RuntimeTypeChecker::checkConstant('App\Config::Data', ['user' => 'User'], 'list', __FILE__, 10) + fn () => RuntimeTypeChecker::checkConstant('App\Config::Data', ['user' => 'User'], 'list', __FILE__, 10) ); expect($res)->toBe(['user' => 'User']); diff --git a/tests/TypeChecking/Boundaries/ConstantContractsTest.php b/tests/TypeChecking/Boundaries/ConstantContractsTest.php index 138faaed..fa080f64 100644 --- a/tests/TypeChecking/Boundaries/ConstantContractsTest.php +++ b/tests/TypeChecking/Boundaries/ConstantContractsTest.php @@ -284,4 +284,281 @@ class ExactLineConfig } }); }); -}); \ No newline at end of file + + describe('4. Closures in Constants (PHP 8.5+)', function () { + test('throws TypeError when constant closure violates return contract', function () { + if (PHP_VERSION_ID < 80500) { + expect(true)->toBeTrue(); + + return; + } + + $source = <<<'PHP' + require $filePath) + ->toThrow(TypeError::class, 'ConfigConstClosureReturnViolation::Callback(): Return value must be of type int, string \'not_an_int\' returned') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('throws TypeError on direct execution of constant closure (Config::Callback)()', function () { + if (PHP_VERSION_ID < 80500) { + expect(true)->toBeTrue(); + + return; + } + + $source = <<<'PHP' + require $filePath) + ->toThrow(TypeError::class, 'ConfigConstClosureDirectCall::Callback(): Return value must be of type int') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('throws TypeError when constant closure parameter violates contract', function () { + if (PHP_VERSION_ID < 80500) { + expect(true)->toBeTrue(); + + return; + } + + $source = <<<'PHP' + require $filePath) + ->toThrow(TypeError::class, 'ConfigConstClosureParamViolation::Formatter(): Argument $id must be of type positive-int, negative int (-5) given') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('throws TypeError when global constant closure violates return contract', function () { + if (PHP_VERSION_ID < 80500) { + expect(true)->toBeTrue(); + + return; + } + + $source = <<<'PHP' + require $filePath) + ->toThrow(TypeError::class, 'GLOBAL_CONST_CLOSURE(): Return value must be of type int') + ; + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('accepts valid constant closure and executes cleanly', function () { + if (PHP_VERSION_ID < 80500) { + expect(true)->toBeTrue(); + + return; + } + + $source = <<<'PHP' +toBe('user_42'); + } finally { + @unlink($filePath); + @rmdir($tempDir); + } + }); + + test('guarantees zero line-drift when instrumenting closures inside constants', function () { + $source = <<<'PHP' +toBe(\count($origLines)); + + $origIndex = array_search('$landmark = \'line_18_exact\';', array_map('trim', $origLines), true); + $transIndex = array_search('$landmark = \'line_18_exact\';', array_map('trim', $transLines), true); + + expect($transIndex)->toBe($origIndex) + ->and($origIndex)->toBe(17) + ; + }); + + test('eliminates return check when closure return is statically proven valid', function () { + $source = <<<'PHP' +not()->toContain('RuntimeTypeChecker::checkReturn'); + }); + }); +}); From 0364d9d3f285bfd7f92bb1e4958e8d7c35d48569 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Mon, 9 Nov 2026 01:28:17 +0800 Subject: [PATCH 10/11] Refactor constant declarations to remove type hints for arrays and integers in test fixtures --- .../TypeChecking/Boundaries/ConstantContractsTest.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/TypeChecking/Boundaries/ConstantContractsTest.php b/tests/TypeChecking/Boundaries/ConstantContractsTest.php index fa080f64..4ec526d7 100644 --- a/tests/TypeChecking/Boundaries/ConstantContractsTest.php +++ b/tests/TypeChecking/Boundaries/ConstantContractsTest.php @@ -22,7 +22,7 @@ class FixtureBadListConst /** * @var list */ - public const array Data = [ + public const Data = [ 'user' => 'User', 'product' => 'Product', ]; @@ -59,7 +59,7 @@ class FixtureValidListConst /** * @var list */ - public const array Data = [ + public const Data = [ 'User', 'Product', ]; @@ -97,7 +97,7 @@ class FixtureBadScalarConst /** * @var positive-int */ - public const int RETRIES = -5; + public const RETRIES = -5; } PHP; @@ -221,7 +221,7 @@ class ConfigWithDriftCheck /** * @var list */ - public const array Data = [ + public const Data = [ 'user' => 'User', ]; } @@ -257,7 +257,7 @@ class ExactLineConfig /** * @var positive-int */ - public const int FAILING_LINE = -99; + public const FAILING_LINE = -99; } PHP; From caf9ff7098db58ed8097cf2522a5db1e0771a378 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Mon, 9 Nov 2026 01:35:31 +0800 Subject: [PATCH 11/11] Add tests for constant closure parameter and return validation in RuntimeTypeChecker --- tests/Internal/Ast/NodeBuilderTest.php | 44 ++++++++++++++ tests/Internal/RuntimeTypeCheckerTest.php | 70 +++++++++++++++++++++++ 2 files changed, 114 insertions(+) diff --git a/tests/Internal/Ast/NodeBuilderTest.php b/tests/Internal/Ast/NodeBuilderTest.php index 881f43c9..1331515a 100644 --- a/tests/Internal/Ast/NodeBuilderTest.php +++ b/tests/Internal/Ast/NodeBuilderTest.php @@ -99,4 +99,48 @@ ->and($call->args[4]->value->value)->toBe(12) ; }); + + test('createConstantClosureParamCheckCall creates FuncCall node for RuntimeTypeChecker::checkConstantClosureParam', function () { + $paramVar = new Node\Expr\Variable('id'); + + $call = NodeBuilder::createConstantClosureParamCheckCall( + 'App\Config::Formatter', + 'id', + $paramVar, + 'positive-int', + 15 + ); + + expect($call)->toBeInstanceOf(Node\Expr\FuncCall::class) + ->and($call->name->toString())->toBe('TypePHP\Internal\RuntimeTypeChecker::checkConstantClosureParam') + ->and($call->args)->toHaveCount(6) + ->and($call->args[0]->value->value)->toBe('App\Config::Formatter') + ->and($call->args[1]->value->value)->toBe('id') + ->and($call->args[2]->value)->toBe($paramVar) + ->and($call->args[3]->value->value)->toBe('positive-int') + ->and($call->args[4]->value)->toBeInstanceOf(Node\Scalar\MagicConst\File::class) + ->and($call->args[5]->value->value)->toBe(15) + ; + }); + + test('createConstantClosureReturnCheckCall creates FuncCall node for RuntimeTypeChecker::checkConstantClosureReturn', function () { + $valueExpr = new Node\Scalar\String_('test'); + + $call = NodeBuilder::createConstantClosureReturnCheckCall( + 'App\Config::Callback', + $valueExpr, + 'int', + 20 + ); + + expect($call)->toBeInstanceOf(Node\Expr\FuncCall::class) + ->and($call->name->toString())->toBe('TypePHP\Internal\RuntimeTypeChecker::checkConstantClosureReturn') + ->and($call->args)->toHaveCount(5) + ->and($call->args[0]->value->value)->toBe('App\Config::Callback') + ->and($call->args[1]->value)->toBe($valueExpr) + ->and($call->args[2]->value->value)->toBe('int') + ->and($call->args[3]->value)->toBeInstanceOf(Node\Scalar\MagicConst\File::class) + ->and($call->args[4]->value->value)->toBe(20) + ; + }); }); diff --git a/tests/Internal/RuntimeTypeCheckerTest.php b/tests/Internal/RuntimeTypeCheckerTest.php index c2f21d6f..7e6eef3f 100644 --- a/tests/Internal/RuntimeTypeCheckerTest.php +++ b/tests/Internal/RuntimeTypeCheckerTest.php @@ -790,4 +790,74 @@ function vendorAction(): void expect($res)->toBe(['user' => 'User']); }); + + test('checkConstantClosureParam validates arguments and respects config toggles and ignore tags', function () { + $valid = RuntimeTypeChecker::checkConstantClosureParam( + 'App\Config::Formatter', + 'id', + 10, + 'positive-int', + __FILE__, + 15 + ); + expect($valid)->toBe(10); + + $invalid = RuntimeTypeChecker::checkConstantClosureParam( + 'App\Config::Formatter', + 'id', + -5, + 'positive-int', + __FILE__, + 15 + ); + expect($invalid)->toBeInstanceOf(ErrorMessage::class) + ->and($invalid->getMessage())->toContain('App\Config::Formatter(): Argument $id must be of type positive-int') + ; + + Config::set(['params' => false]); + expect(RuntimeTypeChecker::checkConstantClosureParam('App\Config::Formatter', 'id', -5, 'positive-int'))->toBe(-5); + + Config::set(['enabled' => false, 'params' => true]); + expect(RuntimeTypeChecker::checkConstantClosureParam('App\Config::Formatter', 'id', -5, 'positive-int'))->toBe(-5); + + Config::set(['enabled' => true, 'params' => true]); + $ignored = RuntimeCheckerIgnoredCaller::run( + fn () => RuntimeTypeChecker::checkConstantClosureParam('App\Config::Formatter', 'id', -5, 'positive-int') + ); + expect($ignored)->toBe(-5); + }); + + test('checkConstantClosureReturn validates return values and respects config toggles and ignore tags', function () { + $valid = RuntimeTypeChecker::checkConstantClosureReturn( + 'App\Config::Callback', + 42, + 'int', + __FILE__, + 25 + ); + expect($valid)->toBe(42); + + $invalid = RuntimeTypeChecker::checkConstantClosureReturn( + 'App\Config::Callback', + 'not_an_int', + 'int', + __FILE__, + 25 + ); + expect($invalid)->toBeInstanceOf(ErrorMessage::class) + ->and($invalid->getMessage())->toContain('App\Config::Callback(): Return value must be of type int, string \'not_an_int\' returned') + ; + + Config::set(['returns' => false]); + expect(RuntimeTypeChecker::checkConstantClosureReturn('App\Config::Callback', 'not_an_int', 'int'))->toBe('not_an_int'); + + Config::set(['enabled' => false, 'returns' => true]); + expect(RuntimeTypeChecker::checkConstantClosureReturn('App\Config::Callback', 'not_an_int', 'int'))->toBe('not_an_int'); + + Config::set(['enabled' => true, 'returns' => true]); + $ignored = RuntimeCheckerIgnoredCaller::run( + fn () => RuntimeTypeChecker::checkConstantClosureReturn('App\Config::Callback', 'not_an_int', 'int') + ); + expect($ignored)->toBe('not_an_int'); + }); });