Skip to content

Commit b99041f

Browse files
ondrejmirtesclaude
andcommitted
Record try-path definedness as conditional on the catch variable being undefined
At a try/catch join where the catch variable is untracked on the non-catch path and certainly defined at the end of the catch body, its later definedness tells the joined paths apart. Record conditional expression holders with a certainty-No (and, for scopes where any variable can exist, a maybe-defined-null) condition on the catch variable, restoring the non-catch certainty and type of variables the join demoted to maybe-defined. To let such holders fire, the isset()-style falsey specification in MutatingScope::applySpecifiedTypes() now publishes the certainty change into the specified-expressions batch - rescuing the waiting holders around unsetExpression()'s invalidation, which would otherwise drop them at the very specification they wait for. A second catch clause merging into the join drops the holders via the conditional-expressions intersection, so multi-catch stays conservative. Co-authored-by: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CGhnJQpUWRRpg6H5LuWJkA Amp-Thread-ID: https://ampcode.com/threads/T-01a19219-7dd4-76fa-9374-bbfeff99ea56
1 parent b3058f4 commit b99041f

8 files changed

Lines changed: 363 additions & 3 deletions

File tree

‎src/Analyser/MutatingScope.php‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4040,12 +4040,37 @@ public function applySpecifiedTypes(SpecifiedTypes $specifiedTypes): self
40404040
$expr = $issetExpr->getExpr();
40414041

40424042
if ($typeSpecification['sure']) {
4043+
$innerExprString = $scope->getNodeKey($expr);
40434044
$scope = $scope->setExpressionCertaintyKeepingType(
40444045
$expr,
40454046
TrinaryLogic::createMaybe(),
40464047
);
4048+
$specifiedExpressions[$innerExprString] = ExpressionTypeHolder::createMaybe(
4049+
$expr,
4050+
$scope->expressionTypes[$innerExprString]->getType(),
4051+
);
40474052
} else {
4053+
$innerExprString = $scope->getNodeKey($expr);
4054+
// Holders conditioned on this expression being undefined (a
4055+
// certainty-No condition) wait for exactly the specification
4056+
// applied here, but unsetExpression()'s invalidation would drop
4057+
// them before the conditional-expressions matcher below could
4058+
// fire them - carve them out and re-add them afterwards.
4059+
$rescuedHolders = [];
4060+
foreach ($scope->conditionalExpressions as $targetExprString => $targetHolders) {
4061+
foreach ($targetHolders as $holderKey => $conditionalHolder) {
4062+
$conditionHolder = $conditionalHolder->getConditionExpressionTypeHolders()[$innerExprString] ?? null;
4063+
if ($conditionHolder === null || !$conditionHolder->getCertainty()->no()) {
4064+
continue;
4065+
}
4066+
$rescuedHolders[$targetExprString][$holderKey] = $conditionalHolder;
4067+
}
4068+
}
40484069
$scope = $scope->unsetExpression($expr);
4070+
foreach ($rescuedHolders as $targetExprString => $targetHolders) {
4071+
$scope = $scope->addConditionalExpressions((string) $targetExprString, $targetHolders);
4072+
}
4073+
$specifiedExpressions[$innerExprString] = new ExpressionTypeHolder($expr, new ErrorType(), TrinaryLogic::createNo());
40494074
}
40504075
$scopeIsWorkingCopy = false;
40514076

‎src/Analyser/StmtHandler/TryCatchHandler.php‎

Lines changed: 79 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,10 @@
88
use PhpParser\Node\Expr;
99
use PhpParser\Node\Stmt;
1010
use PhpParser\Node\Stmt\TryCatch;
11+
use PhpParser\Node\Expr\Variable;
12+
use PHPStan\Analyser\ConditionalExpressionHolder;
1113
use PHPStan\Analyser\ExpressionResultStorage;
14+
use PHPStan\Analyser\ExpressionTypeHolder;
1215
use PHPStan\Analyser\InternalStatementExitPoint;
1316
use PHPStan\Analyser\InternalStatementResult;
1417
use PHPStan\Analyser\InternalThrowPoint;
@@ -28,8 +31,11 @@
2831
use PHPStan\Node\Variable\VariableWrite;
2932
use PHPStan\Node\VariableAssignNode;
3033
use PHPStan\ShouldNotHappenException;
34+
use PHPStan\TrinaryLogic;
3135
use PHPStan\Turbo\ShadowedByTurboExtension;
36+
use PHPStan\Type\ErrorType;
3237
use PHPStan\Type\NeverType;
38+
use PHPStan\Type\NullType;
3339
use PHPStan\Type\ObjectType;
3440
use PHPStan\Type\TypeCombinator;
3541
use Throwable;
@@ -272,7 +278,13 @@ public function processStmt(
272278
$blockScopes[] = $catchScopeForFinally;
273279
$catchFlows[] = [$originalCatchType, VariableFlow::sequence($catchNode->var !== null ? VariableFlowBuilder::targetWrite($catchNode->var, VariableWrite::KIND_CATCH, $catchScopeForFinally, $storage) : null, $catchScopeResult->getVariableFlow())];
274280

275-
$finalScope = $catchScopeResult->isAlwaysTerminating() ? $finalScope : $catchScopeResult->getScope()->mergeWith($finalScope);
281+
if (!$catchScopeResult->isAlwaysTerminating()) {
282+
$mergedScope = $catchScopeResult->getScope()->mergeWith($finalScope);
283+
if ($variableName !== null && $finalScope !== null) {
284+
$mergedScope = $this->addCatchVariableDefinednessConditionals($mergedScope, $finalScope, $catchScopeResult->getScope(), $variableName);
285+
}
286+
$finalScope = $mergedScope;
287+
}
276288
$alwaysTerminating = $alwaysTerminating && $catchScopeResult->isAlwaysTerminating();
277289
$hasYield = $hasYield || $catchScopeResult->hasYield();
278290
$catchThrowPoints = $catchScopeResult->getThrowPoints();
@@ -362,4 +374,70 @@ public function processStmt(
362374
return new InternalStatementResult($finalScope, hasYield: $hasYield, isAlwaysTerminating: $alwaysTerminating, exitPoints: $exitPoints, throwPoints: array_merge($throwPoints, $throwPointsForLater), impurePoints: $impurePoints, variableFlow: VariableFlow::tryCatch($branchScopeResult->getVariableFlow(), $catchFlows, $finallyFlow), dependencies: Dependencies::merge(...$dependencies));
363375
}
364376

377+
/**
378+
* The catch variable's definedness after the try/catch tells the two joined
379+
* paths apart: when it is untracked on the non-catch path and certainly
380+
* defined at the end of the catch body, "the catch variable is undefined"
381+
* later implies the non-catch path ran. Record that as conditional
382+
* expression holders with a certainty-No condition on the catch variable,
383+
* restoring the non-catch certainty (and type) of variables the join
384+
* demoted to maybe-defined - e.g. `isset($e) || $var instanceof \DateTime`
385+
* evaluates `$var` only where `$e` is narrowed away.
386+
*/
387+
private function addCatchVariableDefinednessConditionals(
388+
MutatingScope $mergedScope,
389+
MutatingScope $nonCatchScope,
390+
MutatingScope $catchEndScope,
391+
string $variableName,
392+
): MutatingScope
393+
{
394+
$variableExprString = '$' . $variableName;
395+
if (isset($nonCatchScope->expressionTypes[$variableExprString])) {
396+
return $mergedScope;
397+
}
398+
399+
$catchVariableHolder = $catchEndScope->expressionTypes[$variableExprString] ?? null;
400+
if ($catchVariableHolder === null || !$catchVariableHolder->getCertainty()->yes()) {
401+
return $mergedScope;
402+
}
403+
404+
$conditions = [
405+
[
406+
$variableExprString => new ExpressionTypeHolder(new Variable($variableName), new ErrorType(), TrinaryLogic::createNo()),
407+
],
408+
];
409+
if ($catchVariableHolder->getType()->isNull()->no()) {
410+
// In a scope where any variable can exist (e.g. the top level), the
411+
// isset() machinery models "!isset($e)" on a maybe-defined variable as
412+
// "maybe defined, null when defined" instead of unsetting it. That
413+
// state excludes the catch path just the same - it guarantees a
414+
// defined, non-null catch variable.
415+
$conditions[] = [
416+
$variableExprString => ExpressionTypeHolder::createMaybe(new Variable($variableName), new NullType()),
417+
];
418+
}
419+
foreach ($nonCatchScope->expressionTypes as $exprString => $holder) {
420+
if (!$holder->getCertainty()->yes()) {
421+
continue;
422+
}
423+
$expr = $holder->getExpr();
424+
if (!$expr instanceof Variable || !is_string($expr->name)) {
425+
continue;
426+
}
427+
$mergedHolder = $mergedScope->expressionTypes[$exprString] ?? null;
428+
if ($mergedHolder === null || !$mergedHolder->getCertainty()->maybe()) {
429+
continue;
430+
}
431+
432+
$conditionalHolders = [];
433+
foreach ($conditions as $condition) {
434+
$conditionalHolder = new ConditionalExpressionHolder($condition, $holder);
435+
$conditionalHolders[$conditionalHolder->getKey()] = $conditionalHolder;
436+
}
437+
$mergedScope = $mergedScope->addConditionalExpressions((string) $exprString, $conditionalHolders);
438+
}
439+
440+
return $mergedScope;
441+
}
442+
365443
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug6608;
4+
5+
use PHPStan\TrinaryLogic;
6+
use function PHPStan\Testing\assertType;
7+
use function PHPStan\Testing\assertVariableCertainty;
8+
9+
function (string $s): void {
10+
try {
11+
$var = new \DateTime($s);
12+
} catch (\Throwable $e) {}
13+
14+
if (isset($e) || $var instanceof \DateTime) {
15+
}
16+
17+
if (!isset($e)) {
18+
assertVariableCertainty(TrinaryLogic::createYes(), $var);
19+
assertType('DateTime', $var);
20+
} else {
21+
assertVariableCertainty(TrinaryLogic::createMaybe(), $var);
22+
}
23+
};

‎tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -546,4 +546,11 @@ public function testBug11109(): void
546546
$this->analyse([__DIR__ . '/data/bug-11109.php'], []);
547547
}
548548

549+
public function testBug6608(): void
550+
{
551+
$this->cliArgumentsVariablesRegistered = true;
552+
$this->checkMaybeUndefinedVariables = true;
553+
$this->analyse([__DIR__ . '/data/bug-6608.php'], []);
554+
}
555+
549556
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?php declare(strict_types = 1);
2+
3+
try {
4+
$var = new \DateTime('nope');
5+
} catch (\Throwable $e) {}
6+
7+
if (isset($e) || $var instanceof \DateTime) {
8+
}

‎turbo-ext/src/MutatingScope.cpp‎

Lines changed: 85 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7713,20 +7713,104 @@ class MutatingScope
77137713
zend_throw_error(NULL, "phpstan_turbo: IssetExpr::getExpr() did not answer with an object");
77147714
return zv::Val();
77157715
}
7716+
zv::Val innerKey = otherPrivate(scopeObject, PT_LC("getnodekey"), 1, inner.raw(), [&](MutatingScope &other) {
7717+
return other.getNodeKey(Z_OBJ_P(inner.raw()));
7718+
});
7719+
if (UNEXPECTED(innerKey.isUndef())) return zv::Val();
7720+
zend_string *innerExprString = keyString(innerKey);
7721+
if (UNEXPECTED(innerExprString == NULL)) return zv::Val();
77167722
zv::Val next;
77177723
if (specification.sure) {
77187724
zv::Args args{inner.raw(), pt_trinary_singleton(PT_TRI_MAYBE)};
77197725
next = otherPrivate(scopeObject, PT_LC("setexpressioncertaintykeepingtype"), 2, args, [&](MutatingScope &other) {
77207726
return other.setExpressionCertaintyKeepingType(Z_OBJ_P(inner.raw()), &args[1]);
77217727
});
7728+
if (UNEXPECTED(next.isUndef())) return zv::Val();
7729+
zend_object *nextObject = requireObject(next, "applySpecifiedTypes");
7730+
if (UNEXPECTED(nextObject == NULL)) return zv::Val();
7731+
HashTable *table = otherTable(nextObject, PT_MS_PROP_EXPRESSION_TYPES, PT_LC("expressionTypes"));
7732+
if (UNEXPECTED(table == NULL)) return zv::Val();
7733+
zval *innerHolder = zend_symtable_find(table, innerExprString);
7734+
if (UNEXPECTED(innerHolder == NULL)) {
7735+
zend_throw_error(NULL, "Call to a member function getType() on null");
7736+
return zv::Val();
7737+
}
7738+
zv::Val innerType = holderType(zv::Ref(innerHolder));
7739+
if (UNEXPECTED(innerType.isUndef())) return zv::Val();
7740+
zval holder;
7741+
pt_holder_create(&holder, inner.raw(), innerType.raw(), PT_TRI_MAYBE);
7742+
specifiedExpressions.set(innerExprString, zv::Val::adopt(holder));
77227743
} else {
7744+
/* Holders conditioned on this expression being undefined (a
7745+
* certainty-No condition) wait for exactly the specification
7746+
* applied here, but unsetExpression()'s invalidation would
7747+
* drop them before the conditional-expressions matcher below
7748+
* could fire them - carve them out and re-add them afterwards. */
7749+
HashTable *conditionalTable = otherTable(scopeObject, PT_MS_PROP_CONDITIONAL_EXPRESSIONS, PT_LC("conditionalExpressions"));
7750+
if (UNEXPECTED(conditionalTable == NULL)) return zv::Val();
7751+
zv::Arr rescuedHolders = zv::Arr::create(0);
7752+
for (auto targetEntry : zv::TableRef(conditionalTable)) {
7753+
zval *targetHolders = targetEntry.value().deref().raw();
7754+
if (UNEXPECTED(Z_TYPE_P(targetHolders) != IS_ARRAY)) continue;
7755+
zv::Arr rescuedForTarget = zv::Arr::create(0);
7756+
for (auto holderEntry : zv::TableRef(Z_ARRVAL_P(targetHolders))) {
7757+
zval *conditionalHolder = holderEntry.value().deref().raw();
7758+
zv::Val conditions;
7759+
if (EXPECTED(Z_TYPE_P(conditionalHolder) == IS_OBJECT && Z_OBJCE_P(conditionalHolder) == pt_ce_cond_expr_holder)) {
7760+
conditions = zv::Val::copyOf(zv::ObjRef(Z_OBJ_P(conditionalHolder)).propAt(PT_CEH_PROP_CONDS));
7761+
} else {
7762+
if (UNEXPECTED(Z_TYPE_P(conditionalHolder) != IS_OBJECT)) {
7763+
zend_throw_error(NULL, "Call to a member function getConditionExpressionTypeHolders() on %s", zend_zval_value_name(conditionalHolder));
7764+
return zv::Val();
7765+
}
7766+
conditions = pt_type_call(Z_OBJ_P(conditionalHolder), PT_LC("getconditionexpressiontypeholders"), 0, NULL);
7767+
if (UNEXPECTED(conditions.isUndef())) return zv::Val();
7768+
}
7769+
zval *conditionsZv = conditions.raw();
7770+
ZVAL_DEREF(conditionsZv);
7771+
if (UNEXPECTED(Z_TYPE_P(conditionsZv) != IS_ARRAY)) continue;
7772+
zval *conditionHolder = zend_symtable_find(Z_ARRVAL_P(conditionsZv), innerExprString);
7773+
if (conditionHolder == NULL) continue;
7774+
zend_long certainty = holderCertainty(zv::Ref(conditionHolder));
7775+
if (UNEXPECTED(certainty < 0)) return zv::Val();
7776+
if (certainty != PT_TRI_NO) continue;
7777+
Z_TRY_ADDREF_P(conditionalHolder);
7778+
if (holderEntry.stringKeyOrNull() != NULL) {
7779+
zend_hash_update(rescuedForTarget.table(), holderEntry.stringKey(), conditionalHolder);
7780+
} else {
7781+
zend_hash_index_update(rescuedForTarget.table(), holderEntry.indexKey(), conditionalHolder);
7782+
}
7783+
}
7784+
if (zend_hash_num_elements(rescuedForTarget.table()) == 0) continue;
7785+
zval rescuedZv = rescuedForTarget.take();
7786+
if (targetEntry.stringKeyOrNull() != NULL) {
7787+
zend_hash_update(rescuedHolders.table(), targetEntry.stringKey(), &rescuedZv);
7788+
} else {
7789+
zend_hash_index_update(rescuedHolders.table(), targetEntry.indexKey(), &rescuedZv);
7790+
}
7791+
}
7792+
77237793
zval arg;
77247794
ZVAL_COPY_VALUE(&arg, inner.raw());
77257795
next = otherPrivate(scopeObject, PT_LC("unsetexpression"), 1, &arg, [&](MutatingScope &other) {
77267796
return other.unsetExpression(Z_OBJ_P(inner.raw()));
77277797
});
7798+
if (UNEXPECTED(next.isUndef())) return zv::Val();
7799+
for (auto rescuedEntry : zv::TableRef(rescuedHolders.table())) {
7800+
zend_object *nextObject = requireObject(next, "applySpecifiedTypes");
7801+
if (UNEXPECTED(nextObject == NULL)) return zv::Val();
7802+
zv::Str targetExprString = rescuedEntry.stringKeyOrNull() != NULL ? zv::Str::copyOf(rescuedEntry.stringKey()) : zv::Str::adopt(zend_long_to_str((zend_long) rescuedEntry.indexKey()));
7803+
zv::Val added = pt_mutating_scope_add_conditional_expressions(nextObject, targetExprString.get(), Z_ARRVAL_P(rescuedEntry.value().deref().raw()));
7804+
if (UNEXPECTED(added.isUndef())) return zv::Val();
7805+
next = std::move(added);
7806+
}
7807+
zval errorType;
7808+
if (UNEXPECTED(!pt_error_type_new(&errorType))) return zv::Val();
7809+
zv::Val errorTypeHold = zv::Val::adopt(errorType);
7810+
zval holder;
7811+
pt_holder_create(&holder, inner.raw(), errorTypeHold.raw(), PT_TRI_NO);
7812+
specifiedExpressions.set(innerExprString, zv::Val::adopt(holder));
77287813
}
7729-
if (UNEXPECTED(next.isUndef())) return zv::Val();
77307814
zend_object *nextObject = requireObject(next, "applySpecifiedTypes");
77317815
if (UNEXPECTED(nextObject == NULL)) return zv::Val();
77327816
scope = std::move(next);

0 commit comments

Comments
 (0)