Skip to content
Permalink
Browse files

Fix #1391 - find dead code in assignments to self

  • Loading branch information...
muglug committed May 13, 2019
1 parent a3a208a commit 7c2fe5344699ed1a67674f580908eca178804177
Showing with 52 additions and 5 deletions.
  1. +18 −2 src/Psalm/Internal/Analyzer/Statements/Block/LoopAnalyzer.php
  2. +34 −3 tests/UnusedVariableTest.php
@@ -90,6 +90,8 @@ public static function analyze(
$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 @@ public static function analyze(
}
}
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 @@ public static function analyze(
}
$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 @@ public static function analyze(
}
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 {
@@ -594,15 +594,15 @@ function main() : void {
],
'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 @@ function foo() : void {
}',
'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',
],
];
}
}

0 comments on commit 7c2fe53

Please sign in to comment.
You can’t perform that action at this time.