Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions src/Analyser/NodeScopeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -1487,6 +1487,8 @@ private function processStmtNode(
$initScope = $condResult->getScope();
$condResultScope = $condResult->getScope();

// only the last condition expression is relevant whether the loop continues
// see https://www.php.net/manual/en/control-structures.for.php
if ($condExpr === $lastCondExpr) {
$condTruthiness = ($this->treatPhpDocTypesAsCertain ? $condResultScope->getType($condExpr) : $condResultScope->getNativeType($condExpr))->toBoolean();
$isIterableAtLeastOnce = $isIterableAtLeastOnce->and($condTruthiness->isTrue());
Expand All @@ -1513,6 +1515,7 @@ private function processStmtNode(
foreach ($bodyScopeResult->getExitPointsByType(Continue_::class) as $continueExitPoint) {
$bodyScope = $bodyScope->mergeWith($continueExitPoint->getScope());
}

foreach ($stmt->loop as $loopExpr) {
$exprResult = $this->processExprNode($stmt, $loopExpr, $bodyScope, static function (): void {
}, ExpressionContext::createTopLevel());
Expand All @@ -1539,6 +1542,7 @@ private function processStmtNode(
if ($lastCondExpr !== null) {
$alwaysIterates = $alwaysIterates->and($bodyScope->getType($lastCondExpr)->toBoolean()->isTrue());
$bodyScope = $this->processExprNode($stmt, $lastCondExpr, $bodyScope, $nodeCallback, ExpressionContext::createDeep())->getTruthyScope();
$bodyScope = $this->inferForLoopExpressions($stmt, $lastCondExpr, $bodyScope);
}

$finalScopeResult = $this->processStmtNodes($stmt, $stmt->stmts, $bodyScope, $nodeCallback, $context)->filterOutLoopExitPoints();
Expand Down Expand Up @@ -7116,4 +7120,66 @@ public function getFilteringExprForMatchArm(Expr\Match_ $expr, array $conditions
);
}

private function inferForLoopExpressions(For_ $stmt, Expr $lastCondExpr, MutatingScope $bodyScope): MutatingScope
{
// infer $items[$i] type from for ($i = 0; $i < count($items); $i++) {...}

if (
// $i = 0
count($stmt->init) === 1
&& $stmt->init[0] instanceof Assign
&& $stmt->init[0]->var instanceof Variable
&& $stmt->init[0]->expr instanceof Node\Scalar\Int_
&& $stmt->init[0]->expr->value === 0
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we could do >=0

// $i++ or ++$i
&& count($stmt->loop) === 1
&& ($stmt->loop[0] instanceof Expr\PreInc || $stmt->loop[0] instanceof Expr\PostInc)
&& $stmt->loop[0]->var instanceof Variable
) {
// $i < count($items)
if (
$lastCondExpr instanceof BinaryOp\Smaller
&& $lastCondExpr->left instanceof Variable
&& $lastCondExpr->right instanceof FuncCall
&& $lastCondExpr->right->name instanceof Name
&& $lastCondExpr->right->name->toLowerString() === 'count'
&& count($lastCondExpr->right->getArgs()) > 0
&& $lastCondExpr->right->getArgs()[0]->value instanceof Variable
&& is_string($stmt->init[0]->var->name)
&& $stmt->init[0]->var->name === $stmt->loop[0]->var->name
&& $stmt->init[0]->var->name === $lastCondExpr->left->name
) {
$arrayArg = $lastCondExpr->right->getArgs()[0]->value;
$bodyScope = $bodyScope->assignExpression(
new ArrayDimFetch($lastCondExpr->right->getArgs()[0]->value, $lastCondExpr->left),
$bodyScope->getType($arrayArg)->getIterableValueType(),
$bodyScope->getNativeType($arrayArg)->getIterableValueType(),
);
}

// count($items) > $i
if (
$lastCondExpr instanceof BinaryOp\Greater
&& $lastCondExpr->right instanceof Variable
&& $lastCondExpr->left instanceof FuncCall
&& $lastCondExpr->left->name instanceof Name
&& $lastCondExpr->left->name->toLowerString() === 'count'
&& count($lastCondExpr->left->getArgs()) > 0
&& $lastCondExpr->left->getArgs()[0]->value instanceof Variable
&& is_string($stmt->init[0]->var->name)
&& $stmt->init[0]->var->name === $stmt->loop[0]->var->name
&& $stmt->init[0]->var->name === $lastCondExpr->right->name
) {
$arrayArg = $lastCondExpr->left->getArgs()[0]->value;
$bodyScope = $bodyScope->assignExpression(
new ArrayDimFetch($lastCondExpr->left->getArgs()[0]->value, $lastCondExpr->right),
$bodyScope->getType($arrayArg)->getIterableValueType(),
$bodyScope->getNativeType($arrayArg)->getIterableValueType(),
);
}
}

return $bodyScope;
}

}
52 changes: 52 additions & 0 deletions tests/PHPStan/Analyser/nsrt/for-loop-expr.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php declare(strict_types=1);

namespace Bug12807;

use function PHPStan\debugScope;
use function PHPStan\Testing\assertType;

/**
* @param non-empty-list<int> $items
*
* @return non-empty-list<int>
*/
function getItemsWithForLoop(array $items): array
{
for ($i = 0; $i < count($items); $i++) {
$items[$i] = 1;
}

assertType('non-empty-list<int>', $items);
return $items;
}

/**
* @param list<string> $items
*
* @return list<string>
*/
function getItemsWithForLoopInvertLastCond(array $items): array
{
for ($i = 0; count($items) > $i; ++$i) {
$items[$i] = 'hello';
}

assertType('list<string>', $items);
return $items;
}


/**
* @param array<string> $items
*
* @return array<string>
*/
function getItemsArray(array $items): array
{
for ($i = 0; count($items) > $i; ++$i) {
$items[$i] = 'hello';
}

assertType('array<string>', $items);
return $items;
}
Original file line number Diff line number Diff line change
Expand Up @@ -867,16 +867,7 @@ public function testBug12406b(): void
{
$this->reportPossiblyNonexistentGeneralArrayOffset = true;

$this->analyse([__DIR__ . '/data/bug-12406b.php'], [
[
'Offset int<0, max> might not exist on non-empty-list<array{0: string, 1: non-empty-string, 2: non-falsy-string, 3: numeric-string, 4?: numeric-string, 5?: numeric-string}>.',
22,
],
[
'Offset int<0, max> might not exist on non-empty-list<array{0: string, 1: non-empty-string, 2: non-falsy-string, 3: numeric-string, 4?: numeric-string, 5?: numeric-string}>.',
23,
],
]);
$this->analyse([__DIR__ . '/data/bug-12406b.php'], []);
}

public function testBug11679(): void
Expand Down
Loading