Skip to content

Commit

Permalink
Merge pull request #6150 from weirdan/unary-minus-unused-variable
Browse files Browse the repository at this point in the history
Unary plus and minus mark operand as used
  • Loading branch information
weirdan authored Jul 20, 2021
2 parents 9cb963f + 052c747 commit c29092c
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@
namespace Psalm\Internal\Analyzer\Statements\Expression;

use PhpParser;
use PhpParser\Node\Expr\UnaryMinus;
use Psalm\CodeLocation;
use Psalm\Context;
use Psalm\Internal\Analyzer\Statements\ExpressionAnalyzer;
use Psalm\Internal\Analyzer\StatementsAnalyzer;
use Psalm\Internal\Codebase\VariableUseGraph;
use Psalm\Internal\DataFlow\DataFlowNode;
use Psalm\Type;
use Psalm\Type\Atomic\TFloat;
use Psalm\Type\Atomic\TInt;
Expand Down Expand Up @@ -55,6 +59,39 @@ public static function analyze(
$statements_analyzer->node_data->setType($stmt, new Type\Union($acceptable_types));
}

self::addDataFlow(
$statements_analyzer,
$stmt,
$stmt->expr,
$stmt instanceof UnaryMinus ? 'unary-minus' : 'unary-plus'
);

return true;
}

private static function addDataFlow(
StatementsAnalyzer $statements_analyzer,
PhpParser\Node\Expr $stmt,
PhpParser\Node\Expr $value,
string $type
): void {
$result_type = $statements_analyzer->node_data->getType($stmt);
if ($statements_analyzer->data_flow_graph instanceof VariableUseGraph && $result_type) {
$var_location = new CodeLocation($statements_analyzer, $stmt);

$stmt_value_type = $statements_analyzer->node_data->getType($value);

$new_parent_node = DataFlowNode::getForAssignment($type, $var_location);
$statements_analyzer->data_flow_graph->addNode($new_parent_node);
$result_type->parent_nodes = [
$new_parent_node->id => $new_parent_node,
];

if ($stmt_value_type && $stmt_value_type->parent_nodes) {
foreach ($stmt_value_type->parent_nodes as $parent_node) {
$statements_analyzer->data_flow_graph->addPath($parent_node, $new_parent_node, $type);
}
}
}
}
}
20 changes: 20 additions & 0 deletions tests/UnusedCodeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1029,6 +1029,26 @@ public static function foo() : Exception {
throw A::foo();
'
],
'variableUsedAsUnaryMinusOperand' => [
'<?php
function f(): int
{
$a = 1;
$b = -$a;
return $b;
}
',
],
'variableUsedAsUnaryPlusOperand' => [
'<?php
function f(): int
{
$a = 1;
$b = +$a;
return $b;
}
',
],
];
}

Expand Down

0 comments on commit c29092c

Please sign in to comment.