Skip to content

Commit 6ff1b97

Browse files
committed
Add tests for non-standalone post-increment and post-decrement behavior and improve behavior
1 parent c22c264 commit 6ff1b97

2 files changed

Lines changed: 293 additions & 18 deletions

File tree

‎src/Internal/Ast/ContractVisitor.php‎

Lines changed: 102 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ public static function reset(): void
124124
private string $currentNamespace = '';
125125

126126
/**
127-
* @var list<array{name: ?string, isAnonymous: bool, hasInheritance: bool, hasRealInheritance: bool, hasPropertyWithDoc: bool, isReadonly: bool, isFinal: bool, hasTemplates: bool, isTrait?: bool, aliases?: array<string, TypeNode>, templates?: array<string, TemplateTagValueNode>}>
127+
* @var list<array{name: ?string, isAnonymous: bool, hasInheritance: bool, hasRealInheritance: bool, hasPropertyWithDoc: bool, isReadonly: bool, isFinal: bool, hasTemplates: bool, isTrait?: bool, aliases?: array<string, TypeNode>, templates?: array<string, TemplateTagValueNode>, unannotatedProps?: array<string, true>}>
128128
*/
129129
private array $classStack = [];
130130

@@ -309,8 +309,20 @@ public function enterNode(Node $node): Node|array|null
309309
return $this->handleExpression($node);
310310
}
311311

312-
if ($node instanceof Node\Expr\ArrowFunction) {
313-
$node->expr->setAttribute('typephp_is_standalone', true);
312+
if ($node instanceof Node\Stmt\For_) {
313+
$doc = $node->getDocComment();
314+
if ($doc !== null && str_contains($doc->getText(), '@var')) {
315+
$this->scopeManager->extractVarDocblock($doc->getText());
316+
}
317+
318+
foreach ($node->init as $initExpr) {
319+
$initExpr->setAttribute('typephp_is_standalone', true);
320+
}
321+
foreach ($node->loop as $loopExpr) {
322+
$loopExpr->setAttribute('typephp_is_standalone', true);
323+
}
324+
325+
return null;
314326
}
315327

316328
if ($node instanceof Node\Stmt\Foreach_) {
@@ -404,10 +416,6 @@ public function leaveNode(Node $node): Node|array|null
404416
}
405417

406418
if ($node instanceof Node\Expr\PreInc || $node instanceof Node\Expr\PostInc || $node instanceof Node\Expr\PreDec || $node instanceof Node\Expr\PostDec) {
407-
if (($node instanceof Node\Expr\PostInc || $node instanceof Node\Expr\PostDec) && $node->getAttribute('typephp_is_standalone') !== true) {
408-
return null;
409-
}
410-
411419
$replacement = $this->handleIncDec($node);
412420
if ($replacement !== null) {
413421
return $replacement;
@@ -1154,13 +1162,15 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\
11541162
$hasInheritance = true;
11551163
}
11561164

1157-
if ($typeName !== null && ($node instanceof Node\Stmt\Class_ || $node instanceof Node\Stmt\Trait_)) {
1165+
$declaredPropsWithoutDoc = [];
1166+
1167+
if ($node instanceof Node\Stmt\Class_ || $node instanceof Node\Stmt\Trait_) {
11581168
foreach ($node->stmts as $stmt) {
11591169
if ($stmt instanceof Node\Stmt\Property) {
11601170
$pDoc = $stmt->getDocComment();
11611171
if ($pDoc !== null && str_contains($pDoc->getText(), '@var')) {
11621172
$varTag = DocblockExtractor::extractVarTagFromDoc($pDoc->getText());
1163-
if ($varTag !== null) {
1173+
if ($varTag !== null && $typeName !== null) {
11641174
foreach ($stmt->props as $p) {
11651175
$propName = $p->name->toString();
11661176
$this->localClassPropertyTypes[$typeName][$propName] = $varTag[0];
@@ -1169,6 +1179,13 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\
11691179
}
11701180
}
11711181
}
1182+
} elseif (! $stmt->isStatic()) {
1183+
foreach ($stmt->props as $p) {
1184+
$propName = $p->name->toString();
1185+
if ($typeName === null || ! StubManager::hasPropertyStub($typeName, $propName)) {
1186+
$declaredPropsWithoutDoc[$propName] = true;
1187+
}
1188+
}
11721189
}
11731190
} elseif ($stmt instanceof Node\Stmt\ClassMethod && strtolower($stmt->name->toString()) === '__construct') {
11741191
$methodDoc = $stmt->getDocComment();
@@ -1192,18 +1209,21 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\
11921209
if ($pType === null && $methodParamTags !== null && isset($methodParamTags[$paramName])) {
11931210
$pType = $methodParamTags[$paramName]->type;
11941211
}
1195-
if ($pType !== null) {
1212+
if ($pType !== null && $typeName !== null) {
11961213
$this->localClassPropertyTypes[$typeName][$paramName] = (string) $pType;
11971214
if ($shortName !== null) {
11981215
$this->localClassPropertyTypes[$shortName][$paramName] = (string) $pType;
11991216
}
1217+
} elseif ($pType === null && ($typeName === null || ! StubManager::hasPropertyStub($typeName, $paramName))) {
1218+
$declaredPropsWithoutDoc[$paramName] = true;
12001219
}
12011220
}
12021221
}
12031222
}
12041223
}
12051224
}
12061225

1226+
$hasMagicPropertyDoc = $doc !== null && str_contains($doc->getText(), '@property');
12071227
$classAliases = $this->extractClassLikeAliases($node, $doc, $typeName);
12081228

12091229
$this->classStack[] = [
@@ -1218,6 +1238,7 @@ private function enterClassLike(Node\Stmt\Class_|Node\Stmt\Interface_|Node\Stmt\
12181238
'isTrait' => $isTrait,
12191239
'aliases' => $classAliases,
12201240
'templates' => $templates,
1241+
'unannotatedProps' => (! $hasRealInheritance && ! $isTrait && ! $hasMagicPropertyDoc) ? $declaredPropsWithoutDoc : [],
12211242
];
12221243
}
12231244

@@ -2366,28 +2387,91 @@ private static function rhsNeedsParensInBinaryOp(Node\Expr $expr): bool
23662387
private function handleIncDec(Node\Expr\PreInc|Node\Expr\PostInc|Node\Expr\PreDec|Node\Expr\PostDec $node): ?Node\Expr
23672388
{
23682389
$isInc = $node instanceof Node\Expr\PreInc || $node instanceof Node\Expr\PostInc;
2390+
$isPost = $node instanceof Node\Expr\PostInc || $node instanceof Node\Expr\PostDec;
2391+
$isStandalone = $node->getAttribute('typephp_is_standalone') === true;
23692392
$binaryClass = $isInc ? Node\Expr\BinaryOp\Plus::class : Node\Expr\BinaryOp\Minus::class;
23702393

2371-
if ($this->targetHasSideEffects($node->var)) {
2372-
$preAssignments = [];
2373-
$cleanTarget = $this->hoistImpureTarget($node->var, $preAssignments);
2374-
$binaryExpr = new $binaryClass(clone $cleanTarget, new Node\Scalar\LNumber(1));
2394+
/** @var list<Node\Expr\Assign|Node\Expr\AssignRef> $preAssignments */
2395+
$preAssignments = [];
2396+
$hasSideEffects = $this->targetHasSideEffects($node->var);
2397+
$cleanTarget = $hasSideEffects
2398+
? $this->hoistImpureTarget($node->var, $preAssignments)
2399+
: $node->var;
2400+
2401+
if ($isPost && ! $isStandalone) {
2402+
if ($this->isProvablyUnannotatedThisProperty($cleanTarget)) {
2403+
return null;
2404+
}
2405+
2406+
$oldVar = new Node\Expr\Variable('__typephpOld' . $this->hoistTempCounter);
2407+
$binaryExpr = new $binaryClass(clone $oldVar, new Node\Scalar\LNumber(1));
23752408
$wrapped = $this->wrapTargetMutation(clone $cleanTarget, $binaryExpr, $node->var->getStartLine());
23762409

23772410
if ($wrapped === null) {
23782411
return null;
23792412
}
23802413

2414+
$this->hoistTempCounter++;
23812415
$this->markWriteContext($cleanTarget);
2416+
$preAssignments[] = new Node\Expr\Assign(clone $oldVar, clone $cleanTarget);
2417+
$preAssignments[] = new Node\Expr\Assign($cleanTarget, $wrapped);
23822418

2383-
return $this->wrapWithPreEvaluations($preAssignments, new Node\Expr\Assign($cleanTarget, $wrapped));
2419+
$expr = $this->wrapWithPreEvaluations($preAssignments, $oldVar);
2420+
$expr->setAttribute('typephp_needs_parens', true);
2421+
2422+
return $expr;
23842423
}
23852424

2386-
$binaryExpr = new $binaryClass($node->var, new Node\Scalar\LNumber(1));
2425+
$binaryExpr = new $binaryClass(clone $cleanTarget, new Node\Scalar\LNumber(1));
2426+
$wrapped = $this->wrapTargetMutation(clone $cleanTarget, $binaryExpr, $node->var->getStartLine());
23872427

2388-
$wrapped = $this->wrapTargetMutation($node->var, $binaryExpr, $node->var->getStartLine());
2428+
if ($wrapped === null) {
2429+
return null;
2430+
}
2431+
2432+
if ($hasSideEffects) {
2433+
$this->markWriteContext($cleanTarget);
2434+
}
2435+
2436+
$assignExpr = new Node\Expr\Assign($cleanTarget, $wrapped);
2437+
$result = $preAssignments !== []
2438+
? $this->wrapWithPreEvaluations($preAssignments, $assignExpr)
2439+
: $assignExpr;
2440+
2441+
if (! $isStandalone) {
2442+
$result->setAttribute('typephp_needs_parens', true);
2443+
}
2444+
2445+
return $result;
2446+
}
2447+
2448+
private function isProvablyUnannotatedThisProperty(Node\Expr $target): bool
2449+
{
2450+
if (! Config::isEliminateStaticallyProvenChecksEnabled()) {
2451+
return false;
2452+
}
2453+
2454+
if (
2455+
! ($target instanceof Node\Expr\PropertyFetch)
2456+
|| ! ($target->var instanceof Node\Expr\Variable)
2457+
|| $target->var->name !== 'this'
2458+
|| ! ($target->name instanceof Node\Identifier)
2459+
) {
2460+
return false;
2461+
}
2462+
2463+
if ($this->classStack === []) {
2464+
return false;
2465+
}
2466+
2467+
$classInfo = end($this->classStack);
2468+
if (($classInfo['isTrait'] ?? false) || ($classInfo['hasRealInheritance'] ?? true)) {
2469+
return false;
2470+
}
2471+
2472+
$propName = $target->name->toString();
23892473

2390-
return $wrapped !== null ? new Node\Expr\Assign($node->var, $wrapped) : null;
2474+
return isset($classInfo['unannotatedProps'][$propName]);
23912475
}
23922476

23932477
private function targetHasSideEffects(Node $node): bool
Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,191 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use TypePHP\Exception\TypeError as TypePHPTypeError;
6+
7+
class IncDecCounter
8+
{
9+
/**
10+
* @var positive-int
11+
*/
12+
public int $count = 1;
13+
14+
/**
15+
* @var int<1, 3>
16+
*/
17+
public int $bounded = 3;
18+
19+
/**
20+
* @var positive-int
21+
*/
22+
public static int $staticCount = 1;
23+
}
24+
25+
function incDecReturnCounterPostDec(IncDecCounter $counter): int
26+
{
27+
return $counter->count--;
28+
}
29+
30+
describe('Non-Standalone Post-Increment and Post-Decrement', function () {
31+
test('rejects non-standalone post-decrement violating @var positive-int on assignment', function () {
32+
/** @var positive-int $count */
33+
$count = 1;
34+
35+
expect(function () use (&$count): int {
36+
$old = $count--;
37+
38+
return $old;
39+
})->toThrow(TypePHPTypeError::class);
40+
});
41+
42+
test('rejects non-standalone post-increment violating @var int<1, 3> on assignment', function () {
43+
/** @var int<1, 3> $count */
44+
$count = 3;
45+
46+
expect(function () use (&$count): int {
47+
$old = $count++;
48+
49+
return $old;
50+
})->toThrow(TypePHPTypeError::class);
51+
});
52+
53+
test('preserves post-increment and post-decrement old return value when valid', function () {
54+
/** @var positive-int $count */
55+
$count = 2;
56+
57+
$oldDec = $count--;
58+
expect($oldDec)->toBe(2)
59+
->and($count)->toBe(1)
60+
;
61+
62+
$oldInc = $count++;
63+
expect($oldInc)->toBe(1)
64+
->and($count)->toBe(2)
65+
;
66+
});
67+
68+
test('preserves post-decrement old return value inside an arrow function', function () {
69+
$counter = new IncDecCounter();
70+
$counter->count = 2;
71+
72+
$fn = static fn (): int => $counter->count--;
73+
74+
// RED: ArrowFunction marks expr as typephp_is_standalone = true, returning 1 instead of 2
75+
expect($fn())->toBe(2)
76+
->and($counter->count)->toBe(1)
77+
;
78+
});
79+
80+
test('rejects non-standalone post-decrement on instance and static properties', function () {
81+
$counter = new IncDecCounter();
82+
$counter->count = 1;
83+
84+
expect(function () use ($counter): int {
85+
$old = $counter->count--;
86+
87+
return $old;
88+
})->toThrow(TypePHPTypeError::class);
89+
90+
IncDecCounter::$staticCount = 1;
91+
92+
expect(function (): int {
93+
$old = IncDecCounter::$staticCount--;
94+
95+
return $old;
96+
})->toThrow(TypePHPTypeError::class);
97+
});
98+
99+
test('evaluates impure receiver once and validates non-standalone property post-decrement', function () {
100+
$counter = new IncDecCounter();
101+
$counter->count = 2;
102+
$calls = 0;
103+
104+
$getCounter = static function () use ($counter, &$calls): IncDecCounter {
105+
$calls++;
106+
107+
return $counter;
108+
};
109+
110+
$old = $getCounter()->count--;
111+
expect($calls)->toBe(1)
112+
->and($old)->toBe(2)
113+
->and($counter->count)->toBe(1)
114+
;
115+
116+
expect(static function () use ($getCounter): int {
117+
return $getCounter()->count--;
118+
})->toThrow(TypePHPTypeError::class);
119+
120+
expect($calls)->toBe(2);
121+
});
122+
123+
test('rejects post-decrement violation in return statement while preserving valid return value', function () {
124+
$validCounter = new IncDecCounter();
125+
$validCounter->count = 2;
126+
127+
expect(incDecReturnCounterPostDec($validCounter))->toBe(2)
128+
->and($validCounter->count)->toBe(1)
129+
;
130+
131+
$invalidCounter = new IncDecCounter();
132+
$invalidCounter->count = 1;
133+
134+
expect(static fn (): int => incDecReturnCounterPostDec($invalidCounter))
135+
->toThrow(TypePHPTypeError::class)
136+
;
137+
});
138+
139+
test('rejects post-increment and post-decrement violations in for-loop and while-loop expressions', function () {
140+
expect(function (): void {
141+
/** @var int<0, 2> $i */
142+
for ($i = 0; $i < 3; $i++) {
143+
}
144+
})->toThrow(TypePHPTypeError::class);
145+
146+
expect(function (): void {
147+
/** @var positive-int $n */
148+
$n = 1;
149+
while ($n-- > 0) {
150+
}
151+
})->toThrow(TypePHPTypeError::class);
152+
});
153+
154+
test('preserves operator precedence and validates post-increment in array index and arithmetic expressions', function () {
155+
/** @var int<0, 1> $idx */
156+
$idx = 0;
157+
$items = ['first', 'second'];
158+
159+
$picked = $items[$idx++];
160+
expect($picked)->toBe('first')
161+
->and($idx)->toBe(1)
162+
;
163+
164+
expect(function () use (&$idx, $items): string {
165+
return $items[$idx++];
166+
})->toThrow(TypePHPTypeError::class);
167+
168+
/** @var int<1, 5> $n */
169+
$n = 2;
170+
$calc = $n++ * 10;
171+
expect($calc)->toBe(20)
172+
->and($n)->toBe(3)
173+
;
174+
});
175+
176+
test('rejects non-standalone post-decrement violating array shape field contract', function () {
177+
/** @var array{count: positive-int} $state */
178+
$state = ['count' => 2];
179+
180+
$old = $state['count']--;
181+
expect($old)->toBe(2)
182+
->and($state['count'])->toBe(1)
183+
;
184+
185+
expect(function () use (&$state): int {
186+
$nextOld = $state['count']--;
187+
188+
return $nextOld;
189+
})->toThrow(TypePHPTypeError::class);
190+
});
191+
});

0 commit comments

Comments
 (0)