From c22c264650f92bff4e3e773ef79a45b765af7882 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Mon, 30 Nov 2026 11:08:37 +0800 Subject: [PATCH 1/2] Enhance type inference and error handling in ParamChecker; add Closure template binding preservation tests --- src/Internal/Checker/ParamChecker.php | 48 +++- src/Internal/Generics/TemplateManager.php | 22 ++ ...ClosureTemplateBindingPreservationTest.php | 270 ++++++++++++++++++ 3 files changed, 332 insertions(+), 8 deletions(-) create mode 100644 tests/TypeChecking/Generics/ClosureTemplateBindingPreservationTest.php diff --git a/src/Internal/Checker/ParamChecker.php b/src/Internal/Checker/ParamChecker.php index 9fdaf7d..d18490d 100644 --- a/src/Internal/Checker/ParamChecker.php +++ b/src/Internal/Checker/ParamChecker.php @@ -340,7 +340,10 @@ public static function checkParams( $selfVerifiedParams = []; if ($allTemplates !== [] && $paramsUseGenerics && ($contract['paramsNeedPreInference'] ?? true)) { - self::preInferGenericTemplates($contract['types'], $vars, $effectiveFunction, $thisObj, $allTemplates, $classTemplates, $selfVerifiedParams); + $preInferErr = self::preInferGenericTemplates($contract['types'], $vars, $effectiveFunction, $thisObj, $allTemplates, $classTemplates, $selfVerifiedParams); + if ($preInferErr !== null) { + return $preInferErr; + } } $boundTemplates = []; @@ -815,9 +818,9 @@ private static function preInferGenericTemplates( array $templates, array $classTemplates = [], array &$selfVerifiedParams = [] - ): void { + ): ?ErrorMessage { if ($types === []) { - return; + return null; } $mask = self::$preInferMaskCache[$effectiveFunction] ??= self::computePreInferMask($types); @@ -825,7 +828,10 @@ private static function preInferGenericTemplates( if (($mask & 1) !== 0) { foreach ($vars as $v) { if ($v instanceof \Closure) { - self::inferTemplatesFromClosures($types, $vars, $effectiveFunction, $thisObj, $templates, $classTemplates); + $err = self::inferTemplatesFromClosures($types, $vars, $effectiveFunction, $thisObj, $templates, $classTemplates); + if ($err !== null) { + return $err; + } break; } @@ -843,6 +849,8 @@ private static function preInferGenericTemplates( if (($mask & 8) !== 0) { self::inferTemplatesFromGenericObjects($types, $vars, $effectiveFunction, $thisObj, $templates, $classTemplates); } + + return null; } /** @@ -930,10 +938,10 @@ private static function inferTemplatesFromClosures( ?object $thisObj, array $templates, array $classTemplates = [] - ): void { + ): ?ErrorMessage { $callableNodes = self::callableNodesFor($effectiveFunction, $types); if (\count($callableNodes) === 0) { - return; + return null; } foreach ($callableNodes as $cParamName => $cTypeNode) { @@ -956,9 +964,31 @@ private static function inferTemplatesFromClosures( if ($inferredCandidate !== null) { if ($targetObj !== null) { $existingType = TemplateManager::getInstanceBoundTypeFast($targetObj, $tName); - if ($existingType !== null && TemplateManager::checkVariance($existingType, $inferredCandidate, GenericTypeNode::VARIANCE_COVARIANT)) { - continue; + if ($existingType !== null) { + $canRefine = TemplateManager::isFallbackBound($targetObj, $tName) + || TemplateManager::isUnspecializedType($existingType); + + if ($canRefine) { + if ( + TemplateManager::checkVariance($existingType, $inferredCandidate, GenericTypeNode::VARIANCE_COVARIANT) + || ! TemplateManager::checkVariance($inferredCandidate, $existingType, GenericTypeNode::VARIANCE_COVARIANT) + ) { + continue; + } + } else { + if (! TemplateManager::checkVariance($existingType, $inferredCandidate, GenericTypeNode::VARIANCE_COVARIANT)) { + $cParamLabel = $closureParams[$idx]->getName(); + + return ErrorFactory::createError( + $effectiveFunction . '(): Argument $' . $cParamName . ' callback parameter $' . $cParamLabel . ' must be ' . $existingType . ' (or supertype), ' . $inferredCandidate . ' given' + ); + } + + continue; + } } + } elseif (TemplateManager::isBound($effectiveFunction, null, $tName)) { + continue; } $templateTag = $templates[$tName]; @@ -988,6 +1018,8 @@ private static function inferTemplatesFromClosures( // Silently ignore reflection errors } } + + return null; } /** diff --git a/src/Internal/Generics/TemplateManager.php b/src/Internal/Generics/TemplateManager.php index b81f42c..65cd1da 100644 --- a/src/Internal/Generics/TemplateManager.php +++ b/src/Internal/Generics/TemplateManager.php @@ -3469,6 +3469,28 @@ public static function checkVariance(TypeNode $existing, TypeNode $expected, str return false; } + if ($existing instanceof NullableTypeNode) { + $inner = $existing->type; + while ($inner instanceof NullableTypeNode) { + $inner = $inner->type; + } + $nullNode = self::$nullNode ??= new IdentifierTypeNode('null'); + $existing = $inner instanceof UnionTypeNode + ? new UnionTypeNode([...$inner->types, $nullNode]) + : new UnionTypeNode([$inner, $nullNode]); + } + + if ($expected instanceof NullableTypeNode) { + $inner = $expected->type; + while ($inner instanceof NullableTypeNode) { + $inner = $inner->type; + } + $nullNode = self::$nullNode ??= new IdentifierTypeNode('null'); + $expected = $inner instanceof UnionTypeNode + ? new UnionTypeNode([...$inner->types, $nullNode]) + : new UnionTypeNode([$inner, $nullNode]); + } + if ($expected instanceof GenericTypeNode) { $baseExpected = strtolower((string) $expected->type); if ($baseExpected === 'key-of' || $baseExpected === 'value-of') { diff --git a/tests/TypeChecking/Generics/ClosureTemplateBindingPreservationTest.php b/tests/TypeChecking/Generics/ClosureTemplateBindingPreservationTest.php new file mode 100644 index 0000000..c382667 --- /dev/null +++ b/tests/TypeChecking/Generics/ClosureTemplateBindingPreservationTest.php @@ -0,0 +1,270 @@ + + */ + public function getIterator(): Traversable; +} + +/** + * @template T + * + * @extends ClosureReifyIEnumerable + */ +interface ClosureReifyICollection extends ClosureReifyIEnumerable, Countable +{ + /** + * @param T $item + */ + public function add(mixed $item): void; + + /** + * @return int<0, max> + */ + public function count(): int; +} + +/** + * @template T + * + * @implements ClosureReifyICollection + * @implements ArrayAccess, T> + */ +final class ClosureReifyList implements ClosureReifyICollection, ArrayAccess +{ + /** + * @var list + */ + private array $items = []; + + /** + * @param T $item + */ + public function add(mixed $item): void + { + $this->items[] = $item; + } + + /** + * @return int<0, max> + */ + public function count(): int + { + return \count($this->items); + } + + /** + * @return Traversable + */ + public function getIterator(): Traversable + { + yield from $this->items; + } + + /** + * @param int<0, max> $offset + */ + public function offsetExists(mixed $offset): bool + { + return isset($this->items[$offset]); + } + + /** + * @param int<0, max> $offset + * + * @return T + */ + public function offsetGet(mixed $offset): mixed + { + return $this->items[$offset]; + } + + /** + * @param int<0, max>|null $offset + * @param T $value + */ + public function offsetSet(mixed $offset, mixed $value): void + { + if ($offset === null) { + $this->items[] = $value; + } else { + $this->items[$offset] = $value; + } + } + + /** + * @param int<0, max> $offset + */ + public function offsetUnset(mixed $offset): void + { + array_splice($this->items, $offset, 1); + } + + /** + * @param callable(T): bool $match + * + * @return T|null + */ + public function find(callable $match): mixed + { + foreach ($this->items as $item) { + if ($match($item)) { + return $item; + } + } + + return null; + } + + /** + * @template U + * + * @param callable(T): U $converter + * + * @return ClosureReifyList + */ + public function convertAll(callable $converter): self + { + /** @var ClosureReifyList $out */ + $out = new ClosureReifyList(); + + foreach ($this->items as $item) { + $out->add($converter($item)); + } + + return $out; + } +} + +/** + * @template TArg + * + * @param callable(TArg): void $first + * @param callable(TArg): void $second + * @param TArg $value + * + * @return TArg + */ +function closureReifyApplyPair(callable $first, callable $second, mixed $value): mixed +{ + return $value; +} + +describe('Closure Template Inference Preservation', function () { + test('does not overwrite class template binding when an incompatible closure fails in convertAll', function () { + /** @var ClosureReifyList $users */ + $users = new ClosureReifyList(); + $users->add(new ClosureReifyUser(1)); + + $names = $users->convertAll(static fn (ClosureReifyUser $u): string => "u{$u->id}"); + + expect(TypePHP::getGenericType($users))->toBe(ClosureReifyUser::class) + ->and($users[0])->toBeInstanceOf(ClosureReifyUser::class) + ->and(TypePHP::getGenericType($names))->toBe('string') + ; + + expect(fn () => $names->add(42))->toThrow(TypePHPTypeError::class); + expect(TypePHP::getGenericType($users))->toBe(ClosureReifyUser::class) + ->and($users[0])->toBeInstanceOf(ClosureReifyUser::class) + ; + + expect(fn () => $users->convertAll(static fn (ClosureReifyProduct $p): string => $p->sku)) + ->toThrow(TypeError::class) + ; + + // RED: currently overwritten to ClosureReifyProduct, causing offsetGet(0) to throw TypeError + expect(TypePHP::getGenericType($users))->toBe(ClosureReifyUser::class) + ->and($users[0])->toBeInstanceOf(ClosureReifyUser::class) + ; + }); + + test('rejects subtype closure parameter on concretely bound class template without narrowing binding', function () { + /** @var ClosureReifyList $animals */ + $animals = new ClosureReifyList(); + $animals->add(new ClosureReifyDog('Rex')); + + expect(fn () => $animals->find(static fn (ClosureReifyDog $d): bool => $d->name === 'Rex')) + ->toThrow(TypePHPTypeError::class) + ; + + expect(TypePHP::getGenericType($animals))->toBe(ClosureReifyAnimal::class); + + $cat = new ClosureReifyAnimal('Whiskers'); + $animals->add($cat); + expect($animals[1])->toBe($cat); + }); + + test('does not widen a concretely bound class template when a closure accepts a nullable parameter', function () { + /** @var ClosureReifyList $users */ + $users = new ClosureReifyList(); + $users->add(new ClosureReifyUser(1)); + + $labels = $users->convertAll( + static fn (?ClosureReifyUser $u): string => $u !== null ? "u{$u->id}" : 'none' + ); + + expect($labels[0])->toBe('u1'); + + expect(TypePHP::getGenericType($users))->toBe(ClosureReifyUser::class); + expect(fn () => $users->add(null))->toThrow(TypePHPTypeError::class); + }); + + test('preserves a narrower class template binding when a closure accepts a supertype', function () { + /** @var ClosureReifyList $dogs */ + $dogs = new ClosureReifyList(); + $dogs->add(new ClosureReifyDog('Rex')); + + $labels = $dogs->convertAll(static fn (ClosureReifyAnimal $a): string => $a->name); + + expect($labels[0])->toBe('Rex') + ->and(TypePHP::getGenericType($dogs))->toBe(ClosureReifyDog::class) + ; + + expect(fn () => $dogs->add(new ClosureReifyAnimal('Generic')))->toThrow(TypePHPTypeError::class); + }); + + test('does not allow a second closure parameter to overwrite an already-bound method or function template', function () { + expect(fn () => closureReifyApplyPair( + static function (ClosureReifyDog $d): void { + }, + static function (ClosureReifyAnimal $a): void { + }, + new ClosureReifyAnimal('Generic') + ))->toThrow(TypePHPTypeError::class); + }); +}); From 6ff1b97b626be1c4da2d590c8aa70375aad5b3d3 Mon Sep 17 00:00:00 2001 From: "Reymart A. Calicdan" Date: Mon, 30 Nov 2026 18:06:42 +0800 Subject: [PATCH 2/2] Add tests for non-standalone post-increment and post-decrement behavior and improve behavior --- src/Internal/Ast/ContractVisitor.php | 120 +++++++++-- .../Scalars/NonStandaloneIncDecTest.php | 191 ++++++++++++++++++ 2 files changed, 293 insertions(+), 18 deletions(-) create mode 100644 tests/TypeChecking/Scalars/NonStandaloneIncDecTest.php diff --git a/src/Internal/Ast/ContractVisitor.php b/src/Internal/Ast/ContractVisitor.php index ca6ac7d..15bfac9 100644 --- a/src/Internal/Ast/ContractVisitor.php +++ b/src/Internal/Ast/ContractVisitor.php @@ -124,7 +124,7 @@ public static function reset(): void private string $currentNamespace = ''; /** - * @var list, templates?: array}> + * @var list, templates?: array, unannotatedProps?: array}> */ private array $classStack = []; @@ -309,8 +309,20 @@ public function enterNode(Node $node): Node|array|null return $this->handleExpression($node); } - if ($node instanceof Node\Expr\ArrowFunction) { - $node->expr->setAttribute('typephp_is_standalone', true); + if ($node instanceof Node\Stmt\For_) { + $doc = $node->getDocComment(); + if ($doc !== null && str_contains($doc->getText(), '@var')) { + $this->scopeManager->extractVarDocblock($doc->getText()); + } + + foreach ($node->init as $initExpr) { + $initExpr->setAttribute('typephp_is_standalone', true); + } + foreach ($node->loop as $loopExpr) { + $loopExpr->setAttribute('typephp_is_standalone', true); + } + + return null; } if ($node instanceof Node\Stmt\Foreach_) { @@ -404,10 +416,6 @@ public function leaveNode(Node $node): Node|array|null } if ($node instanceof Node\Expr\PreInc || $node instanceof Node\Expr\PostInc || $node instanceof Node\Expr\PreDec || $node instanceof Node\Expr\PostDec) { - if (($node instanceof Node\Expr\PostInc || $node instanceof Node\Expr\PostDec) && $node->getAttribute('typephp_is_standalone') !== true) { - return null; - } - $replacement = $this->handleIncDec($node); if ($replacement !== null) { return $replacement; @@ -1154,13 +1162,15 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ $hasInheritance = true; } - if ($typeName !== null && ($node instanceof Node\Stmt\Class_ || $node instanceof Node\Stmt\Trait_)) { + $declaredPropsWithoutDoc = []; + + if ($node instanceof Node\Stmt\Class_ || $node instanceof Node\Stmt\Trait_) { foreach ($node->stmts as $stmt) { if ($stmt instanceof Node\Stmt\Property) { $pDoc = $stmt->getDocComment(); if ($pDoc !== null && str_contains($pDoc->getText(), '@var')) { $varTag = DocblockExtractor::extractVarTagFromDoc($pDoc->getText()); - if ($varTag !== null) { + if ($varTag !== null && $typeName !== null) { foreach ($stmt->props as $p) { $propName = $p->name->toString(); $this->localClassPropertyTypes[$typeName][$propName] = $varTag[0]; @@ -1169,6 +1179,13 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ } } } + } elseif (! $stmt->isStatic()) { + foreach ($stmt->props as $p) { + $propName = $p->name->toString(); + if ($typeName === null || ! StubManager::hasPropertyStub($typeName, $propName)) { + $declaredPropsWithoutDoc[$propName] = true; + } + } } } elseif ($stmt instanceof Node\Stmt\ClassMethod && strtolower($stmt->name->toString()) === '__construct') { $methodDoc = $stmt->getDocComment(); @@ -1192,11 +1209,13 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ if ($pType === null && $methodParamTags !== null && isset($methodParamTags[$paramName])) { $pType = $methodParamTags[$paramName]->type; } - if ($pType !== null) { + if ($pType !== null && $typeName !== null) { $this->localClassPropertyTypes[$typeName][$paramName] = (string) $pType; if ($shortName !== null) { $this->localClassPropertyTypes[$shortName][$paramName] = (string) $pType; } + } elseif ($pType === null && ($typeName === null || ! StubManager::hasPropertyStub($typeName, $paramName))) { + $declaredPropsWithoutDoc[$paramName] = true; } } } @@ -1204,6 +1223,7 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ } } + $hasMagicPropertyDoc = $doc !== null && str_contains($doc->getText(), '@property'); $classAliases = $this->extractClassLikeAliases($node, $doc, $typeName); $this->classStack[] = [ @@ -1218,6 +1238,7 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\ 'isTrait' => $isTrait, 'aliases' => $classAliases, 'templates' => $templates, + 'unannotatedProps' => (! $hasRealInheritance && ! $isTrait && ! $hasMagicPropertyDoc) ? $declaredPropsWithoutDoc : [], ]; } @@ -2366,28 +2387,91 @@ private static function rhsNeedsParensInBinaryOp(Node\Expr $expr): bool private function handleIncDec(Node\Expr\PreInc|Node\Expr\PostInc|Node\Expr\PreDec|Node\Expr\PostDec $node): ?Node\Expr { $isInc = $node instanceof Node\Expr\PreInc || $node instanceof Node\Expr\PostInc; + $isPost = $node instanceof Node\Expr\PostInc || $node instanceof Node\Expr\PostDec; + $isStandalone = $node->getAttribute('typephp_is_standalone') === true; $binaryClass = $isInc ? Node\Expr\BinaryOp\Plus::class : Node\Expr\BinaryOp\Minus::class; - if ($this->targetHasSideEffects($node->var)) { - $preAssignments = []; - $cleanTarget = $this->hoistImpureTarget($node->var, $preAssignments); - $binaryExpr = new $binaryClass(clone $cleanTarget, new Node\Scalar\LNumber(1)); + /** @var list $preAssignments */ + $preAssignments = []; + $hasSideEffects = $this->targetHasSideEffects($node->var); + $cleanTarget = $hasSideEffects + ? $this->hoistImpureTarget($node->var, $preAssignments) + : $node->var; + + if ($isPost && ! $isStandalone) { + if ($this->isProvablyUnannotatedThisProperty($cleanTarget)) { + return null; + } + + $oldVar = new Node\Expr\Variable('__typephpOld' . $this->hoistTempCounter); + $binaryExpr = new $binaryClass(clone $oldVar, new Node\Scalar\LNumber(1)); $wrapped = $this->wrapTargetMutation(clone $cleanTarget, $binaryExpr, $node->var->getStartLine()); if ($wrapped === null) { return null; } + $this->hoistTempCounter++; $this->markWriteContext($cleanTarget); + $preAssignments[] = new Node\Expr\Assign(clone $oldVar, clone $cleanTarget); + $preAssignments[] = new Node\Expr\Assign($cleanTarget, $wrapped); - return $this->wrapWithPreEvaluations($preAssignments, new Node\Expr\Assign($cleanTarget, $wrapped)); + $expr = $this->wrapWithPreEvaluations($preAssignments, $oldVar); + $expr->setAttribute('typephp_needs_parens', true); + + return $expr; } - $binaryExpr = new $binaryClass($node->var, new Node\Scalar\LNumber(1)); + $binaryExpr = new $binaryClass(clone $cleanTarget, new Node\Scalar\LNumber(1)); + $wrapped = $this->wrapTargetMutation(clone $cleanTarget, $binaryExpr, $node->var->getStartLine()); - $wrapped = $this->wrapTargetMutation($node->var, $binaryExpr, $node->var->getStartLine()); + if ($wrapped === null) { + return null; + } + + if ($hasSideEffects) { + $this->markWriteContext($cleanTarget); + } + + $assignExpr = new Node\Expr\Assign($cleanTarget, $wrapped); + $result = $preAssignments !== [] + ? $this->wrapWithPreEvaluations($preAssignments, $assignExpr) + : $assignExpr; + + if (! $isStandalone) { + $result->setAttribute('typephp_needs_parens', true); + } + + return $result; + } + + private function isProvablyUnannotatedThisProperty(Node\Expr $target): bool + { + if (! Config::isEliminateStaticallyProvenChecksEnabled()) { + return false; + } + + if ( + ! ($target instanceof Node\Expr\PropertyFetch) + || ! ($target->var instanceof Node\Expr\Variable) + || $target->var->name !== 'this' + || ! ($target->name instanceof Node\Identifier) + ) { + return false; + } + + if ($this->classStack === []) { + return false; + } + + $classInfo = end($this->classStack); + if (($classInfo['isTrait'] ?? false) || ($classInfo['hasRealInheritance'] ?? true)) { + return false; + } + + $propName = $target->name->toString(); - return $wrapped !== null ? new Node\Expr\Assign($node->var, $wrapped) : null; + return isset($classInfo['unannotatedProps'][$propName]); } private function targetHasSideEffects(Node $node): bool diff --git a/tests/TypeChecking/Scalars/NonStandaloneIncDecTest.php b/tests/TypeChecking/Scalars/NonStandaloneIncDecTest.php new file mode 100644 index 0000000..8cbd990 --- /dev/null +++ b/tests/TypeChecking/Scalars/NonStandaloneIncDecTest.php @@ -0,0 +1,191 @@ + + */ + public int $bounded = 3; + + /** + * @var positive-int + */ + public static int $staticCount = 1; +} + +function incDecReturnCounterPostDec(IncDecCounter $counter): int +{ + return $counter->count--; +} + +describe('Non-Standalone Post-Increment and Post-Decrement', function () { + test('rejects non-standalone post-decrement violating @var positive-int on assignment', function () { + /** @var positive-int $count */ + $count = 1; + + expect(function () use (&$count): int { + $old = $count--; + + return $old; + })->toThrow(TypePHPTypeError::class); + }); + + test('rejects non-standalone post-increment violating @var int<1, 3> on assignment', function () { + /** @var int<1, 3> $count */ + $count = 3; + + expect(function () use (&$count): int { + $old = $count++; + + return $old; + })->toThrow(TypePHPTypeError::class); + }); + + test('preserves post-increment and post-decrement old return value when valid', function () { + /** @var positive-int $count */ + $count = 2; + + $oldDec = $count--; + expect($oldDec)->toBe(2) + ->and($count)->toBe(1) + ; + + $oldInc = $count++; + expect($oldInc)->toBe(1) + ->and($count)->toBe(2) + ; + }); + + test('preserves post-decrement old return value inside an arrow function', function () { + $counter = new IncDecCounter(); + $counter->count = 2; + + $fn = static fn (): int => $counter->count--; + + // RED: ArrowFunction marks expr as typephp_is_standalone = true, returning 1 instead of 2 + expect($fn())->toBe(2) + ->and($counter->count)->toBe(1) + ; + }); + + test('rejects non-standalone post-decrement on instance and static properties', function () { + $counter = new IncDecCounter(); + $counter->count = 1; + + expect(function () use ($counter): int { + $old = $counter->count--; + + return $old; + })->toThrow(TypePHPTypeError::class); + + IncDecCounter::$staticCount = 1; + + expect(function (): int { + $old = IncDecCounter::$staticCount--; + + return $old; + })->toThrow(TypePHPTypeError::class); + }); + + test('evaluates impure receiver once and validates non-standalone property post-decrement', function () { + $counter = new IncDecCounter(); + $counter->count = 2; + $calls = 0; + + $getCounter = static function () use ($counter, &$calls): IncDecCounter { + $calls++; + + return $counter; + }; + + $old = $getCounter()->count--; + expect($calls)->toBe(1) + ->and($old)->toBe(2) + ->and($counter->count)->toBe(1) + ; + + expect(static function () use ($getCounter): int { + return $getCounter()->count--; + })->toThrow(TypePHPTypeError::class); + + expect($calls)->toBe(2); + }); + + test('rejects post-decrement violation in return statement while preserving valid return value', function () { + $validCounter = new IncDecCounter(); + $validCounter->count = 2; + + expect(incDecReturnCounterPostDec($validCounter))->toBe(2) + ->and($validCounter->count)->toBe(1) + ; + + $invalidCounter = new IncDecCounter(); + $invalidCounter->count = 1; + + expect(static fn (): int => incDecReturnCounterPostDec($invalidCounter)) + ->toThrow(TypePHPTypeError::class) + ; + }); + + test('rejects post-increment and post-decrement violations in for-loop and while-loop expressions', function () { + expect(function (): void { + /** @var int<0, 2> $i */ + for ($i = 0; $i < 3; $i++) { + } + })->toThrow(TypePHPTypeError::class); + + expect(function (): void { + /** @var positive-int $n */ + $n = 1; + while ($n-- > 0) { + } + })->toThrow(TypePHPTypeError::class); + }); + + test('preserves operator precedence and validates post-increment in array index and arithmetic expressions', function () { + /** @var int<0, 1> $idx */ + $idx = 0; + $items = ['first', 'second']; + + $picked = $items[$idx++]; + expect($picked)->toBe('first') + ->and($idx)->toBe(1) + ; + + expect(function () use (&$idx, $items): string { + return $items[$idx++]; + })->toThrow(TypePHPTypeError::class); + + /** @var int<1, 5> $n */ + $n = 2; + $calc = $n++ * 10; + expect($calc)->toBe(20) + ->and($n)->toBe(3) + ; + }); + + test('rejects non-standalone post-decrement violating array shape field contract', function () { + /** @var array{count: positive-int} $state */ + $state = ['count' => 2]; + + $old = $state['count']--; + expect($old)->toBe(2) + ->and($state['count'])->toBe(1) + ; + + expect(function () use (&$state): int { + $nextOld = $state['count']--; + + return $nextOld; + })->toThrow(TypePHPTypeError::class); + }); +});