Skip to content

Commit

Permalink
Fix #4366 - possibly-undefined vars in finally block should not error
Browse files Browse the repository at this point in the history
  • Loading branch information
muglug committed Oct 19, 2020
1 parent 9e3b069 commit bffa064
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
18 changes: 12 additions & 6 deletions src/Psalm/Internal/Analyzer/Statements/Block/TryAnalyzer.php
Expand Up @@ -128,7 +128,11 @@ public static function analyze(
foreach ($context->vars_in_scope as $var_id => $type) {
if (!isset($try_context->vars_in_scope[$var_id])) {
$try_context->vars_in_scope[$var_id] = clone $type;
$try_context->vars_in_scope[$var_id]->from_docblock = true;

if (!$stmt->catches) {
$context->vars_in_scope[$var_id]->possibly_undefined = true;
$context->vars_in_scope[$var_id]->possibly_undefined_from_try = true;
}
} else {
$try_context->vars_in_scope[$var_id] = Type::combineUnionTypes(
$try_context->vars_in_scope[$var_id],
Expand Down Expand Up @@ -470,11 +474,13 @@ function ($fq_catch_class) use ($codebase): Type\Atomic {
}
}

foreach ($definitely_newly_assigned_var_ids as $var_id => $_) {
if (isset($context->vars_in_scope[$var_id])) {
$new_type = clone $context->vars_in_scope[$var_id];
$new_type->possibly_undefined_from_try = false;
$context->vars_in_scope[$var_id] = $new_type;
if ($stmt->catches) {
foreach ($definitely_newly_assigned_var_ids as $var_id => $_) {
if (isset($context->vars_in_scope[$var_id])) {
$new_type = clone $context->vars_in_scope[$var_id];
$new_type->possibly_undefined_from_try = false;
$context->vars_in_scope[$var_id] = $new_type;
}
}
}

Expand Down
23 changes: 23 additions & 0 deletions tests/TryCatchTest.php
Expand Up @@ -391,6 +391,29 @@ public function handle(string $arg): string
}
}'
],
'finallyArgMaybeUndefined' => [
'<?php
class TestMe {
private function startTransaction(): void {
}
private function endTransaction(bool $commit): void {
echo $commit ? "Committing" : "Rolling back";
}
public function doWork(): void {
$this->startTransaction();
try {
$this->workThatMayOrMayNotThrow();
$success = true;
} finally {
$this->endTransaction($success ?? false);
}
}
private function workThatMayOrMayNotThrow(): void {}
}'
]
];
}

Expand Down

0 comments on commit bffa064

Please sign in to comment.