Skip to content

Commit

Permalink
Infer type from known ternary condition.
Browse files Browse the repository at this point in the history
  • Loading branch information
AndrolGenhald committed Dec 13, 2021
1 parent df7d1eb commit 49599d2
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -274,12 +274,12 @@ function ($c) use ($reconciled_expression_clauses): bool {
);

$lhs_type = null;

$stmt_cond_type = $statements_analyzer->node_data->getType($stmt->cond);
if ($stmt->if) {
if ($stmt_if_type = $statements_analyzer->node_data->getType($stmt->if)) {
$lhs_type = $stmt_if_type;
}
} elseif ($stmt_cond_type = $statements_analyzer->node_data->getType($stmt->cond)) {
} elseif ($stmt_cond_type) {
$if_return_type_reconciled = AssertionReconciler::reconcile(
'!falsy',
clone $stmt_cond_type,
Expand All @@ -295,7 +295,13 @@ function ($c) use ($reconciled_expression_clauses): bool {
}

if ($lhs_type && ($stmt_else_type = $statements_analyzer->node_data->getType($stmt->else))) {
$statements_analyzer->node_data->setType($stmt, Type::combineUnionTypes($lhs_type, $stmt_else_type));
if ($stmt_cond_type !== null && $stmt_cond_type->isAlwaysFalsy()) {
$statements_analyzer->node_data->setType($stmt, $stmt_else_type);
} elseif ($stmt_cond_type !== null && $stmt_cond_type->isAlwaysTruthy()) {
$statements_analyzer->node_data->setType($stmt, $lhs_type);
} else {
$statements_analyzer->node_data->setType($stmt, Type::combineUnionTypes($lhs_type, $stmt_else_type));
}
} else {
$statements_analyzer->node_data->setType($stmt, Type::getMixed());
}
Expand Down
2 changes: 0 additions & 2 deletions tests/ConstantTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -618,8 +618,6 @@ class B extends A {
class Clazz {
/**
* @var 0|1
*
* @psalm-suppress RedundantCondition
*/
const cons2 = (cons1) ? 1 : 0;
Expand Down

0 comments on commit 49599d2

Please sign in to comment.