1
0
mirror of https://github.com/danog/psalm.git synced 2024-11-27 04:45:20 +01:00

Makes BooleanNot smarter

This commit is contained in:
orklah 2021-09-22 16:49:16 +02:00
parent dd5c2904d8
commit 597e9a99d7
4 changed files with 32 additions and 2 deletions

View File

@ -14,8 +14,7 @@ class BooleanNotAnalyzer
PhpParser\Node\Expr\BooleanNot $stmt,
Context $context
) : bool {
$stmt_type = Type::getBool();
$statements_analyzer->node_data->setType($stmt, $stmt_type);
$inside_negation = $context->inside_negation;
@ -28,7 +27,17 @@ class BooleanNotAnalyzer
$expr_type = $statements_analyzer->node_data->getType($stmt->expr);
if ($expr_type) {
if ($expr_type->isAlwaysTruthy()) {
$stmt_type = Type::getFalse();
} elseif ($expr_type->isAlwaysFalsy()) {
$stmt_type = Type::getTrue();
} else {
$stmt_type = Type::getBool();
}
$stmt_type->from_docblock = $expr_type->from_docblock;
$stmt_type->parent_nodes = $expr_type->parent_nodes;
$statements_analyzer->node_data->setType($stmt, $stmt_type);
}
return $result;

View File

@ -144,6 +144,7 @@ class ArrayFilterReturnTypeProvider implements \Psalm\Plugin\EventHandler\Functi
$key_type->addType(new Type\Atomic\TInt);
}
/** @psalm-suppress TypeDoesNotContainType can be empty after removing above */
if (!$inner_type->getAtomicTypes()) {
return Type::getEmptyArray();
}
@ -296,6 +297,7 @@ class ArrayFilterReturnTypeProvider implements \Psalm\Plugin\EventHandler\Functi
]);
}
/** @psalm-suppress TypeDoesNotContainType can be empty after removing above */
if (!$inner_type->getAtomicTypes()) {
return Type::getEmptyArray();
}

View File

@ -208,6 +208,7 @@ class Reconciler
$negated
);
/** @psalm-suppress TypeDoesNotContainType can be empty after removing above */
if (!$result_type_candidate->getAtomicTypes()) {
$result_type_candidate->addType(new TEmpty);
}
@ -1092,6 +1093,7 @@ class Reconciler
}
}
/** @psalm-suppress TypeDoesNotContainType can be empty after removing above */
if (!$key_type->getAtomicTypes()) {
// this should ideally prompt some sort of error
$key_type->addType(new Type\Atomic\TArrayKey());

View File

@ -3086,6 +3086,23 @@ class ConditionalTest extends \Psalm\Tests\TestCase
}',
'error_message' => 'TypeDoesNotContainType',
],
'BooleanNotOfAlwaysTruthyisFalse' => [
'<?php
class a
{
public function fluent(): self
{
return $this;
}
}
$a = new a();
if (!$a->fluent()) {
echo "always";
}
',
'error_message' => 'TypeDoesNotContainType',
],
];
}
}