Skip to content

Commit 7a23a40

Browse files
committed
Enhance destructuring type propagation for array shapes and implement comprehensive tests for type validation
1 parent a4d5198 commit 7a23a40

3 files changed

Lines changed: 312 additions & 0 deletions

File tree

‎src/Internal/Ast/ContractVisitor.php‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@
66

77
use PhpParser\Node;
88
use PhpParser\NodeVisitorAbstract;
9+
use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode;
10+
use PHPStan\PhpDocParser\Parser\TokenIterator;
911
use TypePHP\Internal\Docblock\DocblockExtractor;
12+
use TypePHP\Internal\Docblock\DocblockNormalizer;
1013
use TypePHP\Internal\Util\Config;
1114

1215
/**
@@ -30,6 +33,11 @@ final class ContractVisitor extends NodeVisitorAbstract
3033
Node\Expr\AssignOp\Coalesce::class => Node\Expr\BinaryOp\Coalesce::class,
3134
];
3235

36+
/**
37+
* @var array<string, array<string|int, string>>
38+
*/
39+
private static array $parsedShapeCache = [];
40+
3341
private ScopeManager $scopeManager;
3442

3543
private string $currentNamespace = '';
@@ -441,6 +449,16 @@ private function handleExpression(Node\Stmt\Expression $node): ?array
441449

442450
/** @var Node\Expr\List_|Node\Expr\Array_ $destructuringVar */
443451
$destructuringVar = $node->expr->var;
452+
453+
// Auto-propagate types from RHS if it's a known ArrayShape in scope
454+
$rhs = $node->expr->expr;
455+
if ($rhs instanceof Node\Expr\Variable && \is_string($rhs->name)) {
456+
$sourceType = $this->scopeManager->getVarTypeFromScope($rhs->name);
457+
if ($sourceType !== null && str_contains($sourceType, '{')) {
458+
$this->propagateShapeTypesToDestructuring($destructuringVar, $sourceType);
459+
}
460+
}
461+
444462
$destructuredVars = $this->extractDestructuringVariables($destructuringVar);
445463
$checkStmts = [];
446464

@@ -463,6 +481,81 @@ private function handleExpression(Node\Stmt\Expression $node): ?array
463481
return $checkStmts !== [] ? [$node, ...$checkStmts] : null;
464482
}
465483

484+
/**
485+
* Propagates field types from an array shape into destructured local variables with O(1) AST memoization.
486+
*/
487+
private function propagateShapeTypesToDestructuring(Node\Expr\List_|Node\Expr\Array_ $destructuringVar, string $shapeTypeString): void
488+
{
489+
try {
490+
$shapeMap = self::$parsedShapeCache[$shapeTypeString] ?? null;
491+
492+
if ($shapeMap === null) {
493+
$normalized = DocblockNormalizer::normalize($shapeTypeString);
494+
[$typeParser, $lexer] = DocblockExtractor::getTypeParserComponents();
495+
$tokens = new TokenIterator($lexer->tokenize($normalized));
496+
$parsed = $typeParser->parse($tokens);
497+
498+
if (! ($parsed instanceof ArrayShapeNode)) {
499+
return;
500+
}
501+
502+
$shapeMap = [];
503+
$autoIdx = 0;
504+
foreach ($parsed->items as $item) {
505+
$key = match (true) {
506+
$item->keyName instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode => $item->keyName->value,
507+
$item->keyName instanceof \PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode => (int) $item->keyName->value,
508+
$item->keyName instanceof \PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode => $item->keyName->name,
509+
$item->keyName !== null => (string) $item->keyName,
510+
default => $autoIdx,
511+
};
512+
513+
if (\is_int($key)) {
514+
$autoIdx = max($autoIdx, $key + 1);
515+
}
516+
517+
$shapeMap[$key] = (string) $item->valueType;
518+
}
519+
520+
self::$parsedShapeCache[$shapeTypeString] = $shapeMap;
521+
}
522+
523+
$currentIdx = 0;
524+
foreach ($destructuringVar->items as $item) {
525+
if ($item === null) {
526+
$currentIdx++;
527+
528+
continue;
529+
}
530+
531+
$destructKey = null;
532+
if ($item->key instanceof Node\Scalar\String_) {
533+
$destructKey = $item->key->value;
534+
} elseif ($item->key instanceof Node\Scalar\LNumber) {
535+
$destructKey = $item->key->value;
536+
$currentIdx = max($currentIdx, $destructKey + 1);
537+
} elseif ($item->key === null) {
538+
$destructKey = $currentIdx;
539+
$currentIdx++;
540+
}
541+
542+
if ($destructKey !== null && isset($shapeMap[$destructKey])) {
543+
$targetVar = $item->value;
544+
$fieldType = $shapeMap[$destructKey];
545+
546+
if ($targetVar instanceof Node\Expr\Variable && \is_string($targetVar->name)) {
547+
$this->scopeManager->registerVarType($targetVar->name, $fieldType);
548+
} elseif ($targetVar instanceof Node\Expr\List_ || $targetVar instanceof Node\Expr\Array_) {
549+
// Recursively propagate nested shape fields
550+
$this->propagateShapeTypesToDestructuring($targetVar, $fieldType);
551+
}
552+
}
553+
}
554+
} catch (\Throwable $e) {
555+
// Silently ignore parsing errors
556+
}
557+
}
558+
466559
private function handleAssign(Node\Expr\Assign $node): void
467560
{
468561
if ($node->var instanceof Node\Expr\Variable && \is_string($node->var->name)) {

‎src/Internal/Ast/ScopeManager.php‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,19 @@ final class ScopeManager
2929
*/
3030
private int $depth = 0;
3131

32+
/**
33+
* Programmatically registers a variable's type into the current scope frame.
34+
* Preserves explicit inline @var declarations in the current frame unless overwrite is true.
35+
*/
36+
public function registerVarType(string $varName, string $typeString, bool $overwrite = false): void
37+
{
38+
if (! $overwrite && isset($this->scopeStack[$this->depth][$varName])) {
39+
return;
40+
}
41+
42+
$this->scopeStack[$this->depth][$varName] = $typeString;
43+
}
44+
3245
/**
3346
* Pushes a new lexical scope frame (O(1)).
3447
*
Lines changed: 206 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,206 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use TypePHP\Exception\TypeError;
6+
7+
describe('Array Shape Destructuring Type Propagation', function () {
8+
describe('Associative Array Shape Destructuring ([\'key\' => $var] = $source)', function () {
9+
test('propagates member types to extracted variables and allows valid reassignments', function () {
10+
/** @var array{id: positive-int, name: non-empty-string} $source */
11+
$source = ['id' => 1, 'name' => 'Alice'];
12+
13+
['id' => $extractedId, 'name' => $extractedName] = $source;
14+
15+
expect($extractedId)->toBe(1)
16+
->and($extractedName)->toBe('Alice')
17+
;
18+
19+
$extractedId = 42;
20+
$extractedName = 'Bob';
21+
22+
expect($extractedId)->toBe(42)
23+
->and($extractedName)->toBe('Bob')
24+
;
25+
});
26+
27+
test('throws TypeError when variable extracted from shape is reassigned to invalid integer', function () {
28+
/** @var array{id: positive-int, name: non-empty-string} $source */
29+
$source = ['id' => 1, 'name' => 'Alice'];
30+
31+
['id' => $extractedId, 'name' => $extractedName] = $source;
32+
33+
expect(function () use (&$extractedId) {
34+
$extractedId = -5;
35+
})->toThrow(TypeError::class, 'Variable $extractedId must be of type positive-int');
36+
37+
expect(function () use (&$extractedId) {
38+
$extractedId = 0;
39+
})->toThrow(TypeError::class, 'Variable $extractedId must be of type positive-int');
40+
});
41+
42+
test('throws TypeError when variable extracted from shape is reassigned to invalid string', function () {
43+
/** @var array{id: positive-int, name: non-empty-string} $source */
44+
$source = ['id' => 1, 'name' => 'Alice'];
45+
46+
['id' => $extractedId, 'name' => $extractedName] = $source;
47+
48+
expect(function () use (&$extractedName) {
49+
$extractedName = '';
50+
})->toThrow(TypeError::class, 'Variable $extractedName must be of type non-empty-string');
51+
});
52+
});
53+
54+
describe('Positional Tuple Destructuring ([$a, $b] = $source)', function () {
55+
test('propagates positional tuple types and prevents invalid reassignments', function () {
56+
/** @var array{positive-int, non-empty-string} $tupleSource */
57+
$tupleSource = [10, 'First'];
58+
59+
[$first, $second] = $tupleSource;
60+
61+
expect($first)->toBe(10)
62+
->and($second)->toBe('First')
63+
;
64+
65+
$first = 99;
66+
$second = 'Updated';
67+
expect($first)->toBe(99)->and($second)->toBe('Updated');
68+
69+
expect(function () use (&$first) {
70+
$first = -10;
71+
})->toThrow(TypeError::class, 'Variable $first must be of type positive-int');
72+
73+
expect(function () use (&$second) {
74+
$second = '';
75+
})->toThrow(TypeError::class, 'Variable $second must be of type non-empty-string');
76+
});
77+
78+
test('propagates types when elements are skipped using empty comma syntax', function () {
79+
/** @var array{positive-int, string, int<1, 100>} $tupleSource */
80+
$tupleSource = [42, 'skipped', 50];
81+
82+
[$first, , $third] = $tupleSource;
83+
84+
expect($first)->toBe(42)
85+
->and($third)->toBe(50)
86+
;
87+
88+
expect(function () use (&$first) {
89+
$first = 0;
90+
})->toThrow(TypeError::class, 'Variable $first must be of type positive-int');
91+
92+
expect(function () use (&$third) {
93+
$third = 150;
94+
})->toThrow(TypeError::class, '<= 100');
95+
});
96+
});
97+
98+
describe('Traditional list(...) Syntax Destructuring', function () {
99+
test('propagates types when using traditional list() syntax with associative keys', function () {
100+
/** @var array{code: positive-int, label: non-empty-string} $data */
101+
$data = ['code' => 200, 'label' => 'OK'];
102+
103+
list('code' => $code, 'label' => $label) = $data;
104+
105+
expect($code)->toBe(200)
106+
->and($label)->toBe('OK')
107+
;
108+
109+
expect(function () use (&$code) {
110+
$code = -1;
111+
})->toThrow(TypeError::class, 'Variable $code must be of type positive-int');
112+
113+
expect(function () use (&$label) {
114+
$label = '';
115+
})->toThrow(TypeError::class, 'Variable $label must be of type non-empty-string');
116+
});
117+
});
118+
119+
describe('Nested Destructuring ([[\'id\' => $id]] = $source)', function () {
120+
test('recursively propagates types through nested array shape destructuring', function () {
121+
/**
122+
* @var array{
123+
* account: array{id: positive-int, role: 'admin'|'user'},
124+
* status: non-empty-string
125+
* } $payload
126+
*/
127+
$payload = [
128+
'account' => ['id' => 100, 'role' => 'admin'],
129+
'status' => 'active',
130+
];
131+
132+
['account' => ['id' => $accountId, 'role' => $accountRole], 'status' => $status] = $payload;
133+
134+
expect($accountId)->toBe(100)
135+
->and($accountRole)->toBe('admin')
136+
->and($status)->toBe('active')
137+
;
138+
139+
$accountRole = 'user';
140+
expect($accountRole)->toBe('user');
141+
142+
expect(function () use (&$accountId) {
143+
$accountId = -99;
144+
})->toThrow(TypeError::class, 'Variable $accountId must be of type positive-int');
145+
146+
expect(function () use (&$accountRole) {
147+
$accountRole = 'superadmin';
148+
})->toThrow(TypeError::class, "('admin' | 'user')");
149+
150+
expect(function () use (&$status) {
151+
$status = '';
152+
})->toThrow(TypeError::class, 'Variable $status must be of type non-empty-string');
153+
});
154+
});
155+
156+
describe('Complex Types Propagated from Shapes (Unions & Refinements)', function () {
157+
test('propagates literal union types and validates reassignment against union', function () {
158+
/** @var array{mode: 'sync'|'async', timeout: int<1, 60>} $options */
159+
$options = ['mode' => 'sync', 'timeout' => 30];
160+
161+
['mode' => $mode, 'timeout' => $timeout] = $options;
162+
163+
$mode = 'async';
164+
$timeout = 10;
165+
expect($mode)->toBe('async')->and($timeout)->toBe(10);
166+
167+
expect(function () use (&$mode) {
168+
$mode = 'deferred';
169+
})->toThrow(TypeError::class, "('sync' | 'async')");
170+
171+
expect(function () use (&$timeout) {
172+
$timeout = 120;
173+
})->toThrow(TypeError::class, '<= 60');
174+
});
175+
});
176+
177+
describe('Non-Regressions & Unannotated Fallbacks', function () {
178+
test('does not interfere with destructuring from untyped raw arrays', function () {
179+
$untyped = ['x' => 1, 'y' => 'hello'];
180+
181+
['x' => $x, 'y' => $y] = $untyped;
182+
183+
expect($x)->toBe(1)->and($y)->toBe('hello');
184+
185+
$x = -50;
186+
$y = '';
187+
expect($x)->toBe(-50)->and($y)->toBe('');
188+
});
189+
190+
test('retaining explicit inline @var on destructuring statement overrides source shape', function () {
191+
/** @var array{id: int, name: string} $source */
192+
$source = ['id' => 10, 'name' => 'Alice'];
193+
194+
/**
195+
* Explicit inline @var refines $id to positive-int:
196+
*
197+
* @var positive-int $id
198+
*/
199+
['id' => $id, 'name' => $name] = $source;
200+
201+
expect(function () use (&$id) {
202+
$id = -1;
203+
})->toThrow(TypeError::class, 'Variable $id must be of type positive-int');
204+
});
205+
});
206+
});

0 commit comments

Comments
 (0)