1
0
mirror of https://github.com/danog/psalm.git synced 2025-01-22 05:41:20 +01:00

Mark as possibly-undefined any variable that wasn’t present when the loop began

Fixes #3332
This commit is contained in:
Brown 2020-05-10 11:17:50 -04:00
parent 28349c6423
commit 55222573ea
2 changed files with 25 additions and 1 deletions

View File

@ -155,6 +155,8 @@ class LoopAnalyzer
$original_mixed_counts = $analyzer->getMixedCountsForFile($statements_analyzer->getFilePath());
$pre_condition_vars_in_scope = $loop_scope->loop_context->vars_in_scope;
IssueBuffer::startRecording();
foreach ($pre_conditions as $condition_offset => $pre_condition) {
@ -315,6 +317,15 @@ class LoopAnalyzer
$analyzer->setMixedCountsForFile($statements_analyzer->getFilePath(), $original_mixed_counts);
IssueBuffer::startRecording();
foreach ($pre_loop_context->vars_in_scope as $var_id => $_) {
if (!isset($pre_condition_vars_in_scope[$var_id])
&& strpos($var_id, '->') === false
&& strpos($var_id, '[') === false
) {
$inner_context->vars_in_scope[$var_id]->possibly_undefined = true;
}
}
foreach ($pre_conditions as $condition_offset => $pre_condition) {
self::applyPreConditionToLoopContext(
$statements_analyzer,

View File

@ -394,7 +394,20 @@ class WhileTest extends \Psalm\Tests\TestCase
$i++;
}
}'
]
],
'possiblyUndefinedInWhile' => [
'<?php
function getRenderersForClass(string $a): void {
/** @psalm-suppress MixedArgument */
while ($b = getString($b ?? $a)) {
$c = "hello";
}
}
function getString(string $s) : ?string {
return rand(0, 1) ? $s : null;
}'
],
];
}