1
0
mirror of https://github.com/danog/psalm.git synced 2024-11-30 04:39:00 +01:00

Fix #1391 - find dead code in assignments to self

This commit is contained in:
Matthew Brown 2019-05-12 23:31:36 -04:00
parent a3a208a7c9
commit 7c2fe53446
2 changed files with 52 additions and 5 deletions

View File

@ -90,6 +90,8 @@ class LoopAnalyzer
$loop_scope->loop_context->parent_context = $loop_scope->loop_parent_context;
$pre_outer_context = $loop_scope->loop_parent_context;
if ($assignment_depth === 0 || $has_break_statement) {
$inner_context = clone $loop_scope->loop_context;
$inner_context->loop_scope = $loop_scope;
@ -252,6 +254,14 @@ class LoopAnalyzer
}
}
if ($inner_context->collect_references) {
foreach ($inner_context->unreferenced_vars as $var_id => $_) {
if (!isset($pre_outer_context->vars_in_scope[$var_id])) {
unset($inner_context->unreferenced_vars[$var_id]);
}
}
}
$loop_scope->loop_parent_context->vars_possibly_in_scope = array_merge(
$inner_context->vars_possibly_in_scope,
$loop_scope->loop_parent_context->vars_possibly_in_scope
@ -423,7 +433,10 @@ class LoopAnalyzer
}
$loop_scope->loop_context->referenced_var_ids = array_merge(
$inner_context->referenced_var_ids,
array_intersect_key(
$inner_context->referenced_var_ids,
$pre_outer_context->vars_in_scope
),
$loop_scope->loop_context->referenced_var_ids
);
@ -437,7 +450,10 @@ class LoopAnalyzer
}
foreach ($inner_context->unreferenced_vars as $var_id => $locations) {
if (!isset($new_referenced_var_ids[$var_id]) || $has_break_statement) {
if (!isset($new_referenced_var_ids[$var_id])
|| !isset($pre_outer_context->vars_in_scope[$var_id])
|| $has_break_statement
) {
if (!isset($loop_scope->loop_context->unreferenced_vars[$var_id])) {
$loop_scope->loop_context->unreferenced_vars[$var_id] = $locations;
} else {

View File

@ -594,15 +594,15 @@ class UnusedVariableTest extends TestCase
],
'loopTypeChangedInIfAndBreakWithReference' => [
'<?php
$a = false;
$a = 1;
while (rand(0, 1)) {
if (rand(0, 1)) {
$a = true;
$a = 2;
break;
}
$a = false;
$a = 3;
}
echo $a;',
@ -1507,6 +1507,37 @@ class UnusedVariableTest extends TestCase
}',
'error_message' => 'UnusedVariable',
],
'detectUnusedVariableInsideLoopAfterAssignment' => [
'<?php
function foo() : void {
foreach ([1, 2, 3] as $i) {
$i = $i;
}
}',
'error_message' => 'UnusedVariable',
],
'detectUnusedVariableInsideLoopAfterAssignmentWithAddition' => [
'<?php
function foo() : void {
foreach ([1, 2, 3] as $i) {
$i = $i + 1;
}
}',
'error_message' => 'UnusedVariable',
],
'detectUnusedVariableInsideLoopCalledInFunction' => [
'<?php
function foo(int $s) : int {
return $s;
}
function bar() : void {
foreach ([1, 2, 3] as $i) {
$i = foo($i);
}
}',
'error_message' => 'UnusedVariable',
],
];
}
}