-
Notifications
You must be signed in to change notification settings - Fork 582
Narrow foreach body to non-empty regardless of polluteScopeWithAlwaysIterableForeach #6094
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: 2.2.x
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -143,6 +143,7 @@ | |
| use PHPStan\ShouldNotHappenException; | ||
| use PHPStan\TrinaryLogic; | ||
| use PHPStan\Type\ClosureType; | ||
| use PHPStan\Type\Constant\ConstantArrayType; | ||
| use PHPStan\Type\Constant\ConstantIntegerType; | ||
| use PHPStan\Type\Constant\ConstantStringType; | ||
| use PHPStan\Type\FileTypeMapper; | ||
|
|
@@ -232,6 +233,8 @@ | |
| private readonly bool $polluteScopeWithLoopInitialAssignments, | ||
| #[AutowiredParameter] | ||
| private readonly bool $polluteScopeWithAlwaysIterableForeach, | ||
| #[AutowiredParameter(ref: '%featureToggles.narrowForeachBodyNonEmpty%')] | ||
| private readonly bool $narrowForeachBodyNonEmpty, | ||
| #[AutowiredParameter] | ||
| private readonly bool $polluteScopeWithBlock, | ||
| #[AutowiredParameter] | ||
|
|
@@ -1453,6 +1456,16 @@ | |
| $stmt->expr, | ||
| new Array_([]), | ||
| ); | ||
| // Inside the loop body the iterated expression is non-empty, so narrow it | ||
| // (list to non-empty-list, array to non-empty-array) at body entry. Under | ||
| // narrowForeachBodyNonEmpty this happens even with | ||
| // polluteScopeWithAlwaysIterableForeach off; the code below then strips the | ||
| // narrowing back out of the after-loop scope, so the "loop always iterated" | ||
| // assumption never leaks past the loop. With the toggle off the body scope | ||
| // matches the old behaviour exactly. | ||
| $bodyIterateeScope = $this->narrowForeachBodyNonEmpty || $this->polluteScopeWithAlwaysIterableForeach | ||
| ? $scope->filterByTruthyValue($arrayComparisonExpr) | ||
| : $scope; | ||
| $this->callNodeCallback($nodeCallback, new InForeachNode($stmt), $scope, $storage); | ||
| $originalScope = $scope; | ||
| $bodyScope = $scope; | ||
|
|
@@ -1475,7 +1488,7 @@ | |
| if ($context->isTopLevel()) { | ||
| $storage = $originalStorage->duplicate(); | ||
|
|
||
| $originalScope = $this->polluteScopeWithAlwaysIterableForeach ? $scope->filterByTruthyValue($arrayComparisonExpr) : $scope; | ||
| $originalScope = $bodyIterateeScope; | ||
| $unrolledResult = $this->tryProcessUnrolledConstantArrayForeach($stmt, $originalScope, $originalStorage, $context); | ||
| if ($unrolledResult !== null) { | ||
| $bodyScope = $unrolledResult['bodyScope']; | ||
|
|
@@ -1486,7 +1499,7 @@ | |
| $count = 0; | ||
| do { | ||
| $prevScope = $bodyScope; | ||
| $bodyScope = $bodyScope->mergeWith($this->polluteScopeWithAlwaysIterableForeach ? $scope->filterByTruthyValue($arrayComparisonExpr) : $scope); | ||
| $bodyScope = $bodyScope->mergeWith($bodyIterateeScope); | ||
| $storage = $originalStorage->duplicate(); | ||
| $bodyScope = $this->enterForeach($bodyScope, $storage, $originalScope, $stmt, $nodeCallback); | ||
| $bodyScopeResult = $this->processStmtNodesInternal($stmt, $stmt->stmts, $bodyScope, $storage, new NoopNodeCallback(), $context->enterDeep())->filterOutLoopExitPoints(); | ||
|
|
@@ -1506,7 +1519,7 @@ | |
| } | ||
| } | ||
|
|
||
| $bodyScope = $bodyScope->mergeWith($this->polluteScopeWithAlwaysIterableForeach ? $scope->filterByTruthyValue($arrayComparisonExpr) : $scope); | ||
| $bodyScope = $bodyScope->mergeWith($bodyIterateeScope); | ||
| $storage = $originalStorage; | ||
| $bodyScope = $this->enterForeach($bodyScope, $storage, $originalScope, $stmt, $nodeCallback); | ||
| $finalPassContext = $unrolledTotalKeys !== null ? $context->enterUnrolledForeach($unrolledTotalKeys) : $context; | ||
|
|
@@ -1654,6 +1667,39 @@ | |
| } | ||
|
|
||
| $isIterableAtLeastOnce = $exprType->isIterableAtLeastOnce(); | ||
|
|
||
| $iterateeCertainty = $finalScope->hasExpressionType($stmt->expr); | ||
| if ( | ||
| $this->narrowForeachBodyNonEmpty | ||
| && !$this->polluteScopeWithAlwaysIterableForeach | ||
| && !$iterateeCertainty->no() | ||
|
Check warning on line 1675 in src/Analyser/NodeScopeResolver.php
|
||
| && !$isIterableAtLeastOnce->yes() | ||
|
Check warning on line 1676 in src/Analyser/NodeScopeResolver.php
|
||
| ) { | ||
| // Keep the in-body narrowing out of the after-loop scope. With | ||
| // polluteScopeWithAlwaysIterableForeach off we cannot assume the loop ran, | ||
| // so restore the possibly-empty-ness of the iterated expression (keeping any | ||
| // element types the body refined). The loop-exit merge then builds the same | ||
| // conservative scope it would without the narrowing, and does not treat the | ||
| // value variable as always defined after the loop. | ||
| // | ||
| // Strip only the non-emptiness the narrowing added. If the iteratee was | ||
| // already non-empty before the loop ($isIterableAtLeastOnce->yes()), that | ||
| // holds regardless of the loop, so keep it. A literal like | ||
| // `foreach ([1, 2] as $v)` is not a tracked expression, so skip it. | ||
|
Comment on lines
+1678
to
+1688
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. added comments feel too verbose, should be condensed a bit |
||
| $finalIterateeType = $finalScope->getType($stmt->expr); | ||
| if ($finalIterateeType->isArray()->yes()) { | ||
|
Check warning on line 1690 in src/Analyser/NodeScopeResolver.php
|
||
| $finalIterateeNativeType = $finalScope->getNativeType($stmt->expr); | ||
| $finalScope = $finalScope->specifyExpressionType( | ||
| $stmt->expr, | ||
| TypeCombinator::union($finalIterateeType, new ConstantArrayType([], [])), | ||
| $finalIterateeNativeType->isArray()->yes() | ||
|
Check warning on line 1695 in src/Analyser/NodeScopeResolver.php
|
||
| ? TypeCombinator::union($finalIterateeNativeType, new ConstantArrayType([], [])) | ||
| : $finalIterateeNativeType, | ||
| $iterateeCertainty, | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| if ($isIterableAtLeastOnce->maybe() || $exprType->isIterable()->no()) { | ||
| $finalScope = $finalScope->mergeWith($scope->filterByTruthyValue(new BooleanOr( | ||
| new BinaryOp\Identical( | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -239,9 +239,9 @@ public function accepts(Type $type, bool $strictTypes): AcceptsResult | |
| } | ||
| if ($commonReasons !== null && count($commonReasons) > 0) { | ||
| $decorated = []; | ||
| foreach (array_keys($innerAccepts) as $i) { | ||
| foreach (array_keys($innerAccepts) as $innerAcceptsIndex) { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think we have the same problem here.. this change got necessary because the PR broke
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You're right, and my earlier reply was wrong. Sorry. I checked: The leak flows through conditionals between variables the loop body builds (here With bleedingEdge off (stable),
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. please remove unrelated changes in
|
||
| foreach ($commonReasons as $reason) { | ||
| $decorated[] = sprintf('Type #%d from the union: %s', $i + 1, $reason); | ||
| $decorated[] = sprintf('Type #%d from the union: %s', $innerAcceptsIndex + 1, $reason); | ||
| } | ||
| } | ||
| $result = new AcceptsResult($result->result, $decorated); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| <?php declare(strict_types = 1); | ||
|
|
||
| namespace PHPStan\Analyser; | ||
|
|
||
| use PHPStan\Testing\TypeInferenceTestCase; | ||
| use PHPUnit\Framework\Attributes\DataProvider; | ||
|
|
||
| class Bug13312NoPolluteTest extends TypeInferenceTestCase | ||
| { | ||
|
|
||
| public static function dataFileAsserts(): iterable | ||
| { | ||
| yield from self::gatherAssertTypes(__DIR__ . '/data/bug-13312-no-pollute.php'); | ||
| } | ||
|
|
||
| /** | ||
| * @param mixed ...$args | ||
| */ | ||
| #[DataProvider('dataFileAsserts')] | ||
| public function testFileAsserts( | ||
| string $assertType, | ||
| string $file, | ||
| ...$args, | ||
| ): void | ||
| { | ||
| $this->assertFileAsserts($assertType, $file, ...$args); | ||
| } | ||
|
|
||
| public static function getAdditionalConfigFiles(): array | ||
| { | ||
| return [ | ||
| __DIR__ . '/bug-13312-no-pollute.neon', | ||
| ]; | ||
| } | ||
|
|
||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| parameters: | ||
| polluteScopeWithAlwaysIterableForeach: false | ||
| featureToggles: | ||
| narrowForeachBodyNonEmpty: true | ||
|
Comment on lines
+2
to
+4
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. do we need more tests with other combinations of this toggles? |
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| <?php declare(strict_types = 1); | ||
|
|
||
| namespace Bug13312NoPollute; | ||
|
|
||
| use function PHPStan\Testing\assertType; | ||
|
|
||
| /** @param list<mixed> $arr */ | ||
| function foo(array $arr): void { | ||
| assertType('list<mixed>', $arr); | ||
| foreach ($arr as $v) { | ||
| assertType('non-empty-list<mixed>', $arr); | ||
| } | ||
| assertType('list<mixed>', $arr); | ||
|
|
||
| for ($i = 0; $i < count($arr); ++$i) { | ||
| assertType('non-empty-list<mixed>', $arr); | ||
| } | ||
| assertType('list<mixed>', $arr); | ||
| } | ||
|
|
||
| /** @param array<string, int> $arr */ | ||
| function fooStringKeyed(array $arr): void { | ||
| assertType('array<string, int>', $arr); | ||
| foreach ($arr as $v) { | ||
| assertType('non-empty-array<string, int>', $arr); | ||
| } | ||
| assertType('array<string, int>', $arr); | ||
| } | ||
|
|
||
| /** @param list<mixed> $arr */ | ||
| function fooReassign(array $arr): void { | ||
| foreach ($arr as $v) { | ||
| $arr = []; | ||
| assertType('array{}', $arr); | ||
| } | ||
| assertType('array{}', $arr); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think extracting
$this->polluteScopeWithAlwaysIterableForeach ? $scope->filterByTruthyValue($arrayComparisonExpr) : $scopeinto a new variable and therefore removing repetative calls to$scope->filterByTruthyValue()is likely a speed optimization worth a separate PR