Skip to content

Commit b3058f4

Browse files
ondrejmirtesclaude
andcommitted
Record definedness of short-circuit operand assignments as conditional on the assigned boolean
When a boolean && / || RHS contains an assignment inside an operand, a truthy && (or falsey ||) result guarantees every short-circuit operand was evaluated. Diff the RHS walk's truthy/falsey continuation scope against the merged after-RHS scope for variables whose certainty is Yes there but only Maybe after the merge, and record conditional expression holders so that narrowing the assigned variable later restores the certainty and type. 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 091c5a7 commit b3058f4

6 files changed

Lines changed: 382 additions & 117 deletions

File tree

‎src/Analyser/ExprHandler/AssignHandler.php‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,12 @@
88
use PhpParser\Node\Expr;
99
use PhpParser\Node\Expr\ArrayDimFetch;
1010
use PhpParser\Node\Expr\Assign;
11+
use PhpParser\Node\Expr\AssignOp;
1112
use PhpParser\Node\Expr\AssignRef;
13+
use PhpParser\Node\Expr\BinaryOp\BooleanAnd;
14+
use PhpParser\Node\Expr\BinaryOp\BooleanOr;
15+
use PhpParser\Node\Expr\BinaryOp\LogicalAnd;
16+
use PhpParser\Node\Expr\BinaryOp\LogicalOr;
1217
use PhpParser\Node\Expr\ConstFetch;
1318
use PhpParser\Node\Expr\FuncCall;
1419
use PhpParser\Node\Expr\List_;
@@ -104,6 +109,7 @@
104109
use function array_slice;
105110
use function count;
106111
use function in_array;
112+
use function is_array;
107113
use function is_float;
108114
use function is_int;
109115
use function is_nan;
@@ -1326,6 +1332,29 @@ public function applyWrite(
13261332
: $this->defaultNarrowingHelper->specifyTypesForNode($scope, $assignedExpr, TypeSpecifierContext::createFalsey());
13271333
$conditionalExpressions = $this->processSureTypesForConditionalExpressionsAfterAssign($nodeScopeResolver, $scope, $storage, $var->name, $conditionalExpressions, $falseySpecifiedTypes, $falseyType, $impurePoints, $assignedExpr, $storedAssignedExprResult);
13281334
$conditionalExpressions = $this->processSureNotTypesForConditionalExpressionsAfterAssign($nodeScopeResolver, $scope, $storage, $var->name, $conditionalExpressions, $falseySpecifiedTypes, $falseyType, $impurePoints, $assignedExpr, $storedAssignedExprResult);
1335+
1336+
// An assignment inside a short-circuit operand may or may not have run
1337+
// (its variable is only maybe-defined after the RHS walk), but a truthy
1338+
// && (or falsey ||) guarantees the right operand was evaluated. The
1339+
// operand walk's truthy/falsey scope knows exactly which variables it
1340+
// defined - record their certainty as a consequence of the assigned
1341+
// boolean, e.g. "$bool = $x && ($var = 'foo'); if ($bool) { … $var … }".
1342+
if (
1343+
$storedAssignedExprResult !== null
1344+
&& (
1345+
$assignedExpr instanceof BooleanAnd
1346+
|| $assignedExpr instanceof BooleanOr
1347+
|| $assignedExpr instanceof LogicalAnd
1348+
|| $assignedExpr instanceof LogicalOr
1349+
)
1350+
&& self::containsVariableAssignment($assignedExpr)
1351+
) {
1352+
if ($assignedExpr instanceof BooleanAnd || $assignedExpr instanceof LogicalAnd) {
1353+
$conditionalExpressions = $this->processDefinednessForConditionalExpressionsAfterAssign($conditionalExpressions, $var->name, $truthyType, $storedAssignedExprResult->getTruthyScope(), $scope);
1354+
} else {
1355+
$conditionalExpressions = $this->processDefinednessForConditionalExpressionsAfterAssign($conditionalExpressions, $var->name, $falseyType, $storedAssignedExprResult->getFalseyScope(), $scope);
1356+
}
1357+
}
13291358
}
13301359

13311360
foreach ([null, false, 0, 0.0, '', '0', []] as $falseyScalar) {
@@ -2142,6 +2171,76 @@ private function processSureNotTypesForConditionalExpressionsAfterAssign(NodeSco
21422171
return $conditionalExpressions;
21432172
}
21442173

2174+
/**
2175+
* Records "if the assigned variable has $variableType, the target variable is
2176+
* certainly defined (with its branch-scope type)" holders for variables whose
2177+
* certainty is Yes in the given branch continuation scope of the RHS (the
2178+
* truthy scope of a `&&`, the falsey scope of a `||` - the scopes where every
2179+
* short-circuit operand was guaranteed evaluated) but only Maybe in the
2180+
* merged after-RHS scope.
2181+
*
2182+
* @param array<string, ConditionalExpressionHolder[]> $conditionalExpressions
2183+
* @return array<string, ConditionalExpressionHolder[]>
2184+
*/
2185+
private function processDefinednessForConditionalExpressionsAfterAssign(
2186+
array $conditionalExpressions,
2187+
string $variableName,
2188+
Type $variableType,
2189+
MutatingScope $branchScope,
2190+
MutatingScope $mergedScope,
2191+
): array
2192+
{
2193+
foreach ($branchScope->expressionTypes as $exprString => $holder) {
2194+
if (!$holder->getCertainty()->yes()) {
2195+
continue;
2196+
}
2197+
$expr = $holder->getExpr();
2198+
if (!$expr instanceof Variable || !is_string($expr->name) || $expr->name === $variableName) {
2199+
continue;
2200+
}
2201+
$mergedHolder = $mergedScope->expressionTypes[$exprString] ?? null;
2202+
if ($mergedHolder === null || !$mergedHolder->getCertainty()->maybe()) {
2203+
continue;
2204+
}
2205+
2206+
$conditionalHolder = new ConditionalExpressionHolder([
2207+
'$' . $variableName => ExpressionTypeHolder::createYes(new Variable($variableName), $variableType),
2208+
], $holder);
2209+
$conditionalExpressions[(string) $exprString][$conditionalHolder->getKey()] = $conditionalHolder;
2210+
}
2211+
2212+
return $conditionalExpressions;
2213+
}
2214+
2215+
/**
2216+
* Whether the expression contains an assignment whose execution short-circuit
2217+
* evaluation may have skipped - a cheap AST gate so the truthy/falsey scope
2218+
* is only derived for boolean RHS expressions that can define a variable.
2219+
*/
2220+
private static function containsVariableAssignment(Node $node): bool
2221+
{
2222+
if ($node instanceof Assign || $node instanceof AssignOp || $node instanceof AssignRef) {
2223+
return true;
2224+
}
2225+
2226+
foreach ($node->getSubNodeNames() as $subNodeName) {
2227+
$subNode = $node->$subNodeName;
2228+
if ($subNode instanceof Node) {
2229+
if (self::containsVariableAssignment($subNode)) {
2230+
return true;
2231+
}
2232+
} elseif (is_array($subNode)) {
2233+
foreach ($subNode as $subNodeItem) {
2234+
if ($subNodeItem instanceof Node && self::containsVariableAssignment($subNodeItem)) {
2235+
return true;
2236+
}
2237+
}
2238+
}
2239+
}
2240+
2241+
return false;
2242+
}
2243+
21452244
/**
21462245
* Current type of a conditional-holder expression, used to refine the holder's
21472246
* projected type. Prefers the tracked scope state over the stored result,
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug11109;
4+
5+
use PHPStan\TrinaryLogic;
6+
use function PHPStan\Testing\assertType;
7+
use function PHPStan\Testing\assertVariableCertainty;
8+
9+
function (): void {
10+
$bool = 1 == random_int(1, 2)
11+
&& 2 == random_int(1, 2)
12+
&& in_array(
13+
'foo',
14+
[$var = 'foo', 'bar']
15+
);
16+
17+
if ($bool) {
18+
// here $bool is true
19+
// so $var must be defined
20+
// because the 3rd condition above must have been fulfilled for the $bool to be true
21+
// so 2nd argument to in_array() must have been computed
22+
assertVariableCertainty(TrinaryLogic::createYes(), $var);
23+
assertType("'foo'", $var);
24+
throw new \Exception($var);
25+
}
26+
27+
assertVariableCertainty(TrinaryLogic::createMaybe(), $var);
28+
};
29+
30+
function (): void {
31+
$bool = 1 == random_int(1, 2)
32+
|| in_array(random_int(1, 2), [$var = 1, 3], true);
33+
34+
if (!$bool) {
35+
assertVariableCertainty(TrinaryLogic::createYes(), $var);
36+
assertType('1', $var);
37+
} else {
38+
assertVariableCertainty(TrinaryLogic::createMaybe(), $var);
39+
}
40+
};

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -539,4 +539,11 @@ public function testDeadCatch(): void
539539
]);
540540
}
541541

542+
public function testBug11109(): void
543+
{
544+
$this->cliArgumentsVariablesRegistered = true;
545+
$this->checkMaybeUndefinedVariables = true;
546+
$this->analyse([__DIR__ . '/data/bug-11109.php'], []);
547+
}
548+
542549
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?php declare(strict_types = 1);
2+
3+
$bool = 1 == random_int(1, 2)
4+
&& 2 == random_int(1, 2)
5+
&& in_array(
6+
'foo',
7+
[$var = 'foo', 'bar']
8+
);
9+
10+
if ($bool) {
11+
// here $bool is true
12+
// so $var must be defined
13+
// because the 3rd condition above must have been fulfilled for the $bool to be true
14+
// so 2nd argument to in_array() must have been computed
15+
throw new \Exception($var);
16+
}

‎turbo-ext/src/AssignHandler.cpp‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,11 @@
2323
#include "support.h"
2424
#include "generated/AssignHandler.h"
2525
#include "generated/PreparedAssignTarget.h"
26+
#include "generated/MutatingScope.h"
2627

2728
namespace slots = ptdecl::AssignHandler::slot;
2829
namespace sigs = ptdecl::AssignHandler::sig;
30+
namespace msSlots = ptdecl::MutatingScope::slot;
2931
#include "zv.h"
3032
#include "TypeTraits.h"
3133
#include "TypeOps.h"
@@ -2058,6 +2060,23 @@ class AssignHandler
20582060
}
20592061
AH_OKB(processSureTypesForConditionalExpressionsAfterAssign(nsr, scope.raw(), storage, varName, conditionalExpressions, falseySpecifiedTypes.raw(), falseyType.raw(), impurePoints.raw(), assignedExpr.raw(), stored));
20602062
AH_OKB(processSureNotTypesForConditionalExpressionsAfterAssign(nsr, scope.raw(), storage, varName, conditionalExpressions, falseySpecifiedTypes.raw(), falseyType.raw(), impurePoints.raw(), assignedExpr.raw(), stored));
2063+
2064+
// An assignment inside a short-circuit operand may or may not have run
2065+
// (its variable is only maybe-defined after the RHS walk), but a truthy
2066+
// && (or falsey ||) guarantees the right operand was evaluated. The
2067+
// operand walk's truthy/falsey scope knows exactly which variables it
2068+
// defined - record their certainty as a consequence of the assigned
2069+
// boolean, e.g. "$bool = $x && ($var = 'foo'); if ($bool) { … $var … }".
2070+
bool isAnd = ahIs(assignedExpr.raw(), PT_CLASS_BOOLEAN_AND_EXPR) || ahIs(assignedExpr.raw(), PT_CLASS_LOGICAL_AND_EXPR);
2071+
bool isOr = !isAnd && (ahIs(assignedExpr.raw(), PT_CLASS_BOOLEAN_OR_EXPR) || ahIs(assignedExpr.raw(), PT_CLASS_LOGICAL_OR_EXPR));
2072+
if (stored != NULL && (isAnd || isOr)) {
2073+
bool containsAssignment;
2074+
AH_OKB(containsVariableAssignment(assignedExpr.raw(), containsAssignment));
2075+
if (containsAssignment) {
2076+
AH_VALB(branchScope, isAnd ? pt_expression_result_get_truthy_scope(stored) : pt_expression_result_get_falsey_scope(stored));
2077+
AH_OKB(processDefinednessForConditionalExpressionsAfterAssign(conditionalExpressions, varName, isAnd ? truthyType.raw() : falseyType.raw(), branchScope.raw(), scope.raw()));
2078+
}
2079+
}
20612080
}
20622081

20632082
for (int falseyIndex = 0; falseyIndex < 7; falseyIndex++) {
@@ -2466,6 +2485,74 @@ class AssignHandler
24662485
return true;
24672486
}
24682487

2488+
/* Records "if the assigned variable has $variableType, the target variable is
2489+
* certainly defined (with its branch-scope type)" holders for variables whose
2490+
* certainty is Yes in the given branch continuation scope of the RHS (the
2491+
* truthy scope of a `&&`, the falsey scope of a `||`) but only Maybe in the
2492+
* merged after-RHS scope. */
2493+
[[nodiscard]] static bool processDefinednessForConditionalExpressionsAfterAssign(zv::Val &conditionalExpressions, zend_string *variableName, zval *variableType, zval *branchScope, zval *mergedScope)
2494+
{
2495+
zval *branchTypes = OBJ_PROP_NUM(Z_OBJ_P(branchScope), msSlots::expressionTypes);
2496+
zval *mergedTypes = OBJ_PROP_NUM(Z_OBJ_P(mergedScope), msSlots::expressionTypes);
2497+
ZVAL_DEREF(branchTypes);
2498+
ZVAL_DEREF(mergedTypes);
2499+
if (UNEXPECTED(Z_TYPE_P(branchTypes) != IS_ARRAY || Z_TYPE_P(mergedTypes) != IS_ARRAY)) {
2500+
pt_throw_should_not_happen();
2501+
return false;
2502+
}
2503+
2504+
for (auto entry : zv::TableRef(Z_ARRVAL_P(branchTypes))) {
2505+
zval *holder = entry.value().deref().raw();
2506+
if (pt_holder_certainty_value(Z_OBJ_P(holder)) != PT_TRI_YES) continue;
2507+
zval *expr = OBJ_PROP_NUM(Z_OBJ_P(holder), PT_ETH_PROP_EXPR);
2508+
ZVAL_DEREF(expr);
2509+
zend_string *name = ahStringVariableName(expr);
2510+
if (name == NULL || zend_string_equals(name, variableName)) continue;
2511+
2512+
zend_string *stringKey = entry.stringKeyOrNull();
2513+
zval *mergedHolder = stringKey != NULL ? zend_hash_find(Z_ARRVAL_P(mergedTypes), stringKey) : zend_hash_index_find(Z_ARRVAL_P(mergedTypes), entry.indexKey());
2514+
if (mergedHolder == NULL) continue;
2515+
ZVAL_DEREF(mergedHolder);
2516+
if (pt_holder_certainty_value(Z_OBJ_P(mergedHolder)) != PT_TRI_MAYBE) continue;
2517+
2518+
AH_VALB(variable, newVariable(variableName));
2519+
AH_VALB(conditionHolder, newExpressionTypeHolder(variable.raw(), variableType, PT_TRI_YES));
2520+
zv::Str conditionKey = zv::Str::adopt(zend_string_concat2(PT_LC("$"), ZSTR_VAL(variableName), ZSTR_LEN(variableName)));
2521+
zv::Val conditions = ahEmptyArray();
2522+
ahSetKey(conditions, conditionKey.get(), conditionHolder.raw());
2523+
AH_VALB(conditionalHolder, newConditionalExpressionHolder(conditions.raw(), holder));
2524+
zv::Str holderKey = zv::Str::adopt(conditionalHolderKey(conditionalHolder.raw()));
2525+
AH_OKB(!holderKey.isNull());
2526+
zv::Str exprString = stringKey != NULL ? zv::Str::copyOf(stringKey) : zv::Str::adopt(zend_long_to_str((zend_long) entry.indexKey()));
2527+
nestedSet(conditionalExpressions, exprString.get(), holderKey.get(), conditionalHolder.raw());
2528+
}
2529+
2530+
return true;
2531+
}
2532+
2533+
/* matcher for containsVariableAssignment() */
2534+
static bool variableAssignmentMatcher(zend_object *node, void *ctx)
2535+
{
2536+
zend_class_entry *assignCe = pt_class(PT_CLASS_ASSIGN_EXPR);
2537+
zend_class_entry *assignOpCe = pt_class(PT_CLASS_ASSIGN_OP_EXPR);
2538+
zend_class_entry *assignRefCe = pt_class(PT_CLASS_ASSIGN_REF_EXPR);
2539+
if (UNEXPECTED(assignCe == NULL || assignOpCe == NULL || assignRefCe == NULL)) {
2540+
static_cast<pt_find_ctx *>(ctx)->failed = true;
2541+
return false;
2542+
}
2543+
return instanceof_function(node->ce, assignCe) || instanceof_function(node->ce, assignOpCe) || instanceof_function(node->ce, assignRefCe);
2544+
}
2545+
2546+
/* Whether the expression contains an assignment whose execution short-circuit
2547+
* evaluation may have skipped - a cheap AST gate so the truthy/falsey scope
2548+
* is only derived for boolean RHS expressions that can define a variable. */
2549+
[[nodiscard]] static bool containsVariableAssignment(zval *node, bool &contains)
2550+
{
2551+
pt_find_ctx ctx = {};
2552+
contains = pt_find_first_recursive(Z_OBJ_P(node), variableAssignmentMatcher, &ctx) != NULL;
2553+
return !ctx.failed;
2554+
}
2555+
24692556
/* (twin 2081) */
24702557
static zv::Val currentTypeForConditionalHolder(zval *nsr, zval *scope, zval *storage, zval *expr, zval *assignedExpr, zval *assignedValueResult)
24712558
{

0 commit comments

Comments
 (0)