Skip to content

Commit

Permalink
better inference of string increment (#5777)
Browse files Browse the repository at this point in the history
* better inference of string increment

* fix combination
  • Loading branch information
orklah committed May 17, 2021
1 parent f6bdeb6 commit 4c4d574
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 7 deletions.
Expand Up @@ -384,9 +384,9 @@ private static function analyzeNonDivOperands(
$has_string_increment = true;

if (!$result_type) {
$result_type = Type::getString();
$result_type = Type::getNonEmptyString();
} else {
$result_type = Type::combineUnionTypes(Type::getString(), $result_type);
$result_type = Type::combineUnionTypes(Type::getNonEmptyString(), $result_type);
}

$has_valid_left_operand = true;
Expand Down
Expand Up @@ -42,7 +42,7 @@ public static function analyze(
$stmt_var_type = $statements_analyzer->node_data->getType($stmt->var);

if ($stmt instanceof PostInc || $stmt instanceof PostDec) {
$statements_analyzer->node_data->setType($stmt, $stmt_var_type ?: Type::getMixed());
$statements_analyzer->node_data->setType($stmt, $stmt_var_type ?? Type::getMixed());
}

if (($stmt_var_type = $statements_analyzer->node_data->getType($stmt->var))
Expand All @@ -64,9 +64,8 @@ public static function analyze(
$context
);

$stmt_type = clone $stmt_var_type;

$statements_analyzer->node_data->setType($stmt, $stmt_type);
$result_type = $return_type ?? Type::getMixed();
$statements_analyzer->node_data->setType($stmt, $result_type);

BinaryOpAnalyzer::addDataFlow(
$statements_analyzer,
Expand All @@ -81,7 +80,7 @@ public static function analyze(
$codebase = $statements_analyzer->getCodebase();

if ($var_id && isset($context->vars_in_scope[$var_id])) {
$context->vars_in_scope[$var_id] = $stmt_type;
$context->vars_in_scope[$var_id] = $result_type;

if ($codebase->find_unused_variables && $stmt->var instanceof PhpParser\Node\Expr\Variable) {
$context->assigned_var_ids[$var_id] = (int) $stmt->var->getAttribute('startFilePos');
Expand Down
12 changes: 12 additions & 0 deletions tests/BinaryOperationTest.php
Expand Up @@ -384,6 +384,18 @@ function scope(){
'$a' => 'string',
],
],
'stringIncrementWithCheck' => [
'<?php
/** @psalm-suppress StringIncrement */
for($a = "a"; $a != "z"; $a++){
if($a === "b"){
echo "b reached";
}
}',
'assertions' => [
'$a===' => 'non-empty-string',
],
],
'nullCoalescingAssignment' => [
'<?php
function foo(?string $s): string {
Expand Down

0 comments on commit 4c4d574

Please sign in to comment.