Skip to content

Commit 0b2405f

Browse files
committed
Enhance scope management and isolation for closures and functions and anonymous classes
1 parent c3b81d0 commit 0b2405f

4 files changed

Lines changed: 192 additions & 11 deletions

File tree

‎src/Internal/Ast/ContractVisitor.php‎

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,22 @@ public function enterNode(Node $node): ?array
6868
{
6969
$this->trackDeclarationEntry($node);
7070

71-
if ($this->isScopeBoundary($node)) {
72-
$this->scopeManager->pushScope();
71+
if ($node instanceof Node\Stmt\Function_ || $node instanceof Node\Stmt\ClassMethod) {
72+
$this->scopeManager->pushScope(isIsolated: true);
73+
} elseif ($node instanceof Node\Expr\Closure) {
74+
$capturedVars = [];
75+
foreach ($node->uses as $u) {
76+
if ($u->var instanceof Node\Expr\Variable && \is_string($u->var->name)) {
77+
$varName = $u->var->name;
78+
$outerType = $this->scopeManager->getVarTypeFromScope($varName);
79+
if ($outerType !== null) {
80+
$capturedVars[$varName] = $outerType;
81+
}
82+
}
83+
}
84+
$this->scopeManager->pushScope(isIsolated: true, initialBindings: $capturedVars);
85+
} elseif ($this->isSoftScopeBoundary($node)) {
86+
$this->scopeManager->pushScope(isIsolated: false);
7387
}
7488

7589
if ($node instanceof Node\Expr\Assign || $node instanceof Node\Expr\AssignOp) {
@@ -601,12 +615,9 @@ private function wrapClone(Node\Expr\Clone_ $node): ?Node\Expr\FuncCall
601615
);
602616
}
603617

604-
private function isScopeBoundary(Node $node): bool
618+
private function isSoftScopeBoundary(Node $node): bool
605619
{
606-
return $node instanceof Node\Stmt\Function_
607-
|| $node instanceof Node\Stmt\ClassMethod
608-
|| $node instanceof Node\Expr\Closure
609-
|| $node instanceof Node\Expr\ArrowFunction
620+
return $node instanceof Node\Expr\ArrowFunction
610621
|| $node instanceof Node\Stmt\If_
611622
|| $node instanceof Node\Stmt\Else_
612623
|| $node instanceof Node\Stmt\ElseIf_
@@ -617,6 +628,14 @@ private function isScopeBoundary(Node $node): bool
617628
|| $node instanceof Node\Stmt\TryCatch;
618629
}
619630

631+
private function isScopeBoundary(Node $node): bool
632+
{
633+
return $node instanceof Node\Stmt\Function_
634+
|| $node instanceof Node\Stmt\ClassMethod
635+
|| $node instanceof Node\Expr\Closure
636+
|| $this->isSoftScopeBoundary($node);
637+
}
638+
620639
private function isDestructuring(Node\Expr $expr): bool
621640
{
622641
return $expr instanceof Node\Expr\List_

‎src/Internal/Ast/ScopeManager.php‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,18 +17,29 @@ final class ScopeManager
1717
*/
1818
private array $scopeStack = [[]];
1919

20+
/**
21+
* Tracks which scope frames are isolated boundaries (functions, methods, closures).
22+
*
23+
* @var list<bool>
24+
*/
25+
private array $isolatedStack = [false];
26+
2027
/**
2128
* Tracks the current scope frame depth.
2229
*/
2330
private int $depth = 0;
2431

2532
/**
26-
* Pushes a new empty lexical scope frame (O(1)).
33+
* Pushes a new lexical scope frame (O(1)).
34+
*
35+
* @param bool $isIsolated Whether this scope is a hard boundary (function, method, closure)
36+
* @param array<string, string> $initialBindings Initial variable contracts (e.g. captured via 'use')
2737
*/
28-
public function pushScope(): void
38+
public function pushScope(bool $isIsolated = false, array $initialBindings = []): void
2939
{
3040
$this->depth++;
31-
$this->scopeStack[] = [];
41+
$this->scopeStack[] = $initialBindings;
42+
$this->isolatedStack[] = $isIsolated;
3243
}
3344

3445
/**
@@ -38,6 +49,7 @@ public function popScope(): void
3849
{
3950
if ($this->depth > 0) {
4051
array_pop($this->scopeStack);
52+
array_pop($this->isolatedStack);
4153
$this->depth--;
4254
}
4355
}
@@ -76,14 +88,19 @@ public function extractVarDocblock(string $docText, ?Node\Expr $expr = null): vo
7688
}
7789

7890
/**
79-
* Resolves a variable type by walking upward through the lexical scope chain.
91+
* Resolves a variable type by walking upward through the lexical scope chain,
92+
* stopping at isolated scope boundaries (functions, methods, closures).
8093
*/
8194
public function getVarTypeFromScope(string $varName): ?string
8295
{
8396
for ($i = $this->depth; $i >= 0; $i--) {
8497
if (isset($this->scopeStack[$i][$varName])) {
8598
return $this->scopeStack[$i][$varName];
8699
}
100+
101+
if ($this->isolatedStack[$i]) {
102+
break;
103+
}
87104
}
88105

89106
return null;

‎tests/TypeChecking/Boundaries/AnonymousClassContractsTest.php‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,4 +139,102 @@ public function find(int $id): array
139139
;
140140
});
141141
});
142+
143+
describe('Anonymous Class Variable Scope Isolation', function () {
144+
test('does not leak outer variable type contracts into anonymous class method local variables', function () {
145+
/** @var positive-int $leaked */
146+
$leaked = 100;
147+
148+
$anon = new class () {
149+
public function process(): string
150+
{
151+
$leaked = 'string_inside_anonymous_class_method';
152+
153+
return $leaked;
154+
}
155+
};
156+
157+
expect($anon->process())->toBe('string_inside_anonymous_class_method')
158+
->and($leaked)->toBe(100)
159+
;
160+
});
161+
162+
test('does not leak outer variable type contracts into anonymous class method parameter reassignment', function () {
163+
/** @var positive-int $label */
164+
$label = 42;
165+
166+
$anon = new class () {
167+
public function format(string $label): string
168+
{
169+
$label = 'FORMATTED: ' . trim($label);
170+
171+
return $label;
172+
}
173+
};
174+
175+
expect($anon->format(' hello '))->toBe('FORMATTED: hello')
176+
->and($label)->toBe(42)
177+
;
178+
});
179+
180+
test('still enforces local @var annotations declared inside anonymous class methods', function () {
181+
$anon = new class () {
182+
public function compute(int $multiplier): int
183+
{
184+
/** @var positive-int $result */
185+
$result = 10 * $multiplier;
186+
187+
return $result;
188+
}
189+
};
190+
191+
expect($anon->compute(2))->toBe(20);
192+
193+
expect(fn () => $anon->compute(-1))
194+
->toThrow(TypeError::class, 'Variable $result must be of type positive-int')
195+
;
196+
});
197+
198+
test('arrow functions inside anonymous class methods capture method scope but do not leak to outer file', function () {
199+
/** @var positive-int $fileScoped */
200+
$fileScoped = 50;
201+
202+
$anon = new class () {
203+
public function execute(): void
204+
{
205+
/** @var non-empty-string $methodScoped */
206+
$methodScoped = 'initial';
207+
208+
$badArrow = fn () => $methodScoped = '';
209+
expect($badArrow)->toThrow(TypeError::class, 'Variable $methodScoped must be of type non-empty-string');
210+
211+
$fileArrow = fn () => $fileScoped = 'not_an_int_string';
212+
expect($fileArrow())->toBe('not_an_int_string');
213+
}
214+
};
215+
216+
$anon->execute();
217+
expect($fileScoped)->toBe(50);
218+
});
219+
220+
test('closures inside anonymous class methods without use clause do not inherit method variables', function () {
221+
$anon = new class () {
222+
public function run(): string
223+
{
224+
/** @var positive-int $counter */
225+
$counter = 10;
226+
227+
$closure = function (): string {
228+
$counter = 'counter_as_string';
229+
230+
return $counter;
231+
};
232+
233+
return $closure();
234+
}
235+
};
236+
237+
expect($anon->run())->toBe('counter_as_string');
238+
});
239+
});
142240
});

‎tests/TypeChecking/Boundaries/ClosureVariableScopeTest.php‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
declare(strict_types=1);
44

5+
use TypePHP\Exception\TypeError;
6+
57
describe('Closure Variable Type Preservation (Arrow Functions & Long Closures)', function () {
68
test('preserves outer variable type contract inside short closures (arrow functions)', function () {
79
/** @var positive-int $id */
@@ -39,4 +41,49 @@
3941

4042
expect($refClosure)->toThrow(TypeError::class, 'Variable $num');
4143
});
44+
45+
test('does not leak outer variable type contract into closures without use clause', function () {
46+
/** @var positive-int $leaked */
47+
$leaked = 100;
48+
49+
$closure = function (): string {
50+
$leaked = 'valid_string_in_isolated_closure_scope';
51+
52+
return $leaked;
53+
};
54+
55+
expect($closure())->toBe('valid_string_in_isolated_closure_scope')
56+
->and($leaked)->toBe(100)
57+
;
58+
});
59+
60+
test('allows assigning negative integers to uncaptured variable in closure', function () {
61+
/** @var positive-int $isolatedCount */
62+
$isolatedCount = 50;
63+
64+
$closure = function (): int {
65+
$isolatedCount = -99;
66+
67+
return $isolatedCount;
68+
};
69+
70+
expect($closure())->toBe(-99)
71+
->and($isolatedCount)->toBe(50)
72+
;
73+
});
74+
75+
test('does not leak outer script variable type contracts into functions', function () {
76+
/** @var positive-int $scriptScopedVar */
77+
$scriptScopedVar = 42;
78+
79+
$fn = function (): string {
80+
$scriptScopedVar = 'completely_different_string';
81+
82+
return $scriptScopedVar;
83+
};
84+
85+
expect($fn())->toBe('completely_different_string')
86+
->and($scriptScopedVar)->toBe(42)
87+
;
88+
});
4289
});

0 commit comments

Comments
 (0)