Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unary plus and minus mark operand as used #6150

Merged
merged 1 commit into from
Jul 20, 2021
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
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