Skip to content
Permalink
Browse files

Fix #2474 - treat free-standing binaryops as ifs instead

  • Loading branch information
muglug committed Dec 16, 2019
1 parent bdbc758 commit bf67c036aaedea55f84022473c3cfebbbfed090f
@@ -5,6 +5,7 @@
use Psalm\Internal\Analyzer\Statements\Expression\Assignment\ArrayAssignmentAnalyzer;
use Psalm\Internal\Analyzer\Statements\ExpressionAnalyzer;
use Psalm\Internal\Analyzer\StatementsAnalyzer;
use Psalm\Internal\Analyzer\Statements\Block\IfAnalyzer;
use Psalm\Internal\Analyzer\TypeAnalyzer;
use Psalm\CodeLocation;
use Psalm\Config;
@@ -66,7 +67,8 @@ public static function analyze(
StatementsAnalyzer $statements_analyzer,
PhpParser\Node\Expr\BinaryOp $stmt,
Context $context,
$nesting = 0
int $nesting = 0,
bool $from_stmt = false
) {
$codebase = $statements_analyzer->getCodebase();

@@ -77,6 +79,26 @@ public static function analyze(
} elseif ($stmt instanceof PhpParser\Node\Expr\BinaryOp\BooleanAnd ||
$stmt instanceof PhpParser\Node\Expr\BinaryOp\LogicalAnd
) {
if ($from_stmt) {
$fake_if_stmt = new PhpParser\Node\Stmt\If_(
$stmt->left,
[
'stmts' => [
new PhpParser\Node\Stmt\Expression(
$stmt->right
)
]
],
$stmt->getAttributes()
);

if (IfAnalyzer::analyze($statements_analyzer, $fake_if_stmt, $context) === false) {
return false;
}

return null;
}

$left_clauses = Algebra::getFormula(
\spl_object_id($stmt->left),
$stmt->left,
@@ -246,6 +268,26 @@ function ($c) {
} elseif ($stmt instanceof PhpParser\Node\Expr\BinaryOp\BooleanOr ||
$stmt instanceof PhpParser\Node\Expr\BinaryOp\LogicalOr
) {
if ($from_stmt) {
$fake_if_stmt = new PhpParser\Node\Stmt\If_(
new PhpParser\Node\Expr\BooleanNot($stmt->left, $stmt->left->getAttributes()),
[
'stmts' => [
new PhpParser\Node\Stmt\Expression(
$stmt->right
)
]
],
$stmt->getAttributes()
);

if (IfAnalyzer::analyze($statements_analyzer, $fake_if_stmt, $context) === false) {
return false;
}

return null;
}

$pre_referenced_var_ids = $context->referenced_var_ids;
$context->referenced_var_ids = [];

@@ -330,7 +330,9 @@ public static function analyze(
if (BinaryOpAnalyzer::analyze(
$statements_analyzer,
$stmt,
$context
$context,
0,
$from_stmt
) === false) {
return false;
}
@@ -2352,6 +2352,32 @@ public static function get(string $k1, string $k2) : ?string {
}
}'
],
'orWithAssignment' => [
'<?php
function maybeString(): ?string {
return rand(0, 10) > 4 ? "test" : null;
}
function test(): string {
$foo = maybeString();
($foo !== null) || ($foo = "");
return $foo;
}'
],
'andWithAssignment' => [
'<?php
function maybeString(): ?string {
return rand(0, 10) > 4 ? "test" : null;
}
function test(): string {
$foo = maybeString();
($foo === null) && ($foo = "");
return $foo;
}'
],
];
}

0 comments on commit bf67c03

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