Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 76 additions & 17 deletions src/Analyser/StmtHandler/ForeachHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,7 @@ static function () use ($condResult, $emptyArrayType): Type {
if ($context->isTopLevel() && $stmt->byRef) {
$finalScope = $finalScope->assignExpression(new ForeachValueByRefExpr($stmt->valueVar), new MixedType(), new MixedType());
}
$finalScope = $this->processByIterateeMember($nodeScopeResolver, $stmt, $entryScope, $originalStorage, $context, $condResult->getType(), $condResult->getNativeType()) ?? $finalScope;

$bindingFlow = VariableFlow::sequence(
$stmt->keyVar !== null ? VariableFlowBuilder::targetRead($stmt->keyVar, $storage, false) : null,
Expand Down Expand Up @@ -727,30 +728,17 @@ private function enterForeach(NodeScopeResolver $nodeScopeResolver, MutatingScop
* a union like `array<int, A>|array<string, B>`. Ties the key, the value
* and the iteratee together by the member: `is_int($key)` narrows `$value`
* to `A` and the iteratee to `array<int, A>`, and narrowing the iteratee to
* a member narrows the key and the value. Only when the members' keys share
* no value, so that the key tells the member.
* a member narrows the key and the value.
*/
private function addIterateeMemberConditionalHolders(MutatingScope $scope, Expr $iteratee, Type $iterateeType, string $keyVarName, string $valueVarName): MutatingScope
{
if (!$iterateeType instanceof UnionType || $iterateeType instanceof BenevolentUnionType || $iterateeType instanceof TemplateType) {
return $scope;
}
$members = $iterateeType->getTypes();
if (count($members) > self::ITERATEE_MEMBERS_LIMIT || !$scope->hasExpressionType($iteratee)->yes()) {
$members = self::getIterateeMembers($scope, $iteratee, $iterateeType);
if ($members === null) {
return $scope;
}
$keyTypes = [];
foreach ($members as $member) {
if (!$member->isArray()->yes() || $member->isConstantArray()->yes()) {
return $scope;
}
$keyType = $member->getIterableKeyType();
foreach ($keyTypes as $otherKeyType) {
if (!$otherKeyType->isSuperTypeOf($keyType)->no()) {
return $scope;
}
}
$keyTypes[] = $keyType;
$keyTypes[] = $member->getIterableKeyType();
}

$iterateeExprString = $scope->getNodeKey($iteratee);
Expand Down Expand Up @@ -811,6 +799,77 @@ private static function writesOffsetWithLoopVariable(Foreach_ $stmt): bool
}) !== null;
}

/**
* The scope after the loop joined from walking it over each member of the
* iteratee: what the body builds from the keys and the values of one
* member, like `$copy[$key] = $value` over `array<int, A>|array<string, B>`,
* stays `array<int, A>|array<string, B>` instead of mixing the members.
*/
private function processByIterateeMember(NodeScopeResolver $nodeScopeResolver, Foreach_ $stmt, MutatingScope $entryScope, ExpressionResultStorage $storage, StatementContext $context, Type $iterateeType, Type $iterateeNativeType): ?MutatingScope
{
if (
!$context->shouldConvergeLoops()
|| $stmt->getDocComment() !== null
|| !$stmt->valueVar instanceof Variable || !is_string($stmt->valueVar->name)
|| !$stmt->keyVar instanceof Variable || !is_string($stmt->keyVar->name)
|| $stmt->byRef
) {
return null;
}
$members = self::getIterateeMembers($entryScope, $stmt->expr, $iterateeType);
if ($members === null) {
return null;
}

$endScope = null;
foreach ($members as $member) {
// each walk converges with heads of its own, as its entry differs from the other walks'
$memberEndScope = $this->processStmt(
$nodeScopeResolver,
$stmt,
$entryScope->specifyExpressionType($stmt->expr, $member, $iterateeNativeType, TrinaryLogic::createYes()),
$storage->duplicate(),
new NoopNodeCallback(),
$context->enterLoopPass(new ConvergedLoopHeads()),
)->getScope();
$endScope = $endScope === null ? $memberEndScope : $endScope->mergeWith($memberEndScope);
}

return $endScope;
}

/**
* The members of an iteratee union of general arrays whose keys share no
* value, so that the key tells the member.
*
* @return list<Type>|null
*/
private static function getIterateeMembers(MutatingScope $scope, Expr $iteratee, Type $iterateeType): ?array
{
if (!$iterateeType instanceof UnionType || $iterateeType instanceof BenevolentUnionType || $iterateeType instanceof TemplateType) {
return null;
}
$members = $iterateeType->getTypes();
if (count($members) > self::ITERATEE_MEMBERS_LIMIT || !$scope->hasExpressionType($iteratee)->yes()) {
return null;
}
$keyTypes = [];
foreach ($members as $member) {
if (!$member->isArray()->yes() || $member->isConstantArray()->yes()) {
return null;
}
$keyType = $member->getIterableKeyType();
foreach ($keyTypes as $otherKeyType) {
if (!$otherKeyType->isSuperTypeOf($keyType)->no()) {
return null;
}
}
$keyTypes[] = $keyType;
}

return $members;
}

/**
* @return array{bodyScope: MutatingScope, endScope: MutatingScope|null, totalKeys: int}|null
*/
Expand Down
53 changes: 53 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-15946.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php // lint >= 8.1

declare(strict_types = 1);

namespace Bug15946Types;

use function PHPStan\Testing\assertType;

/**
* @param array<int, string>|array<string, string> $types
*/
function copyTypes(array $types): void
{
$copy = [];
foreach ($types as $key => $type) {
$copy[$key] = $type;
}

assertType('array<int, string>|array<string, string>', $copy);
}

enum ParameterType { case STRING; }
enum ArrayParameterType { case STRING; }

/**
* @param array<int<0, max>, string|ParameterType|ArrayParameterType>|array<string, string|ParameterType|ArrayParameterType> $types
*/
function nonArrayTypes(array $types): void
{
$nonArrayTypes = [];
foreach ($types as $key => $type) {
if ($type instanceof ArrayParameterType) {
return;
}

$nonArrayTypes[$key] = $type;
}

assertType('array<int<0, max>, Bug15946Types\ParameterType|string>|array<string, Bug15946Types\ParameterType|string>', $nonArrayTypes);
}

/**
* @param array<int, string>|array<string, int> $types
*/
function swapKeysAndValues(array $types): void
{
$flipped = [];
foreach ($types as $key => $type) {
$flipped[$type] = $key;
}

assertType('array<int, string>|array<string, int>', $flipped);
}
7 changes: 7 additions & 0 deletions tests/PHPStan/Rules/Functions/ReturnTypeRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -670,6 +670,13 @@ public function testBug15873(): void
]);
}

public function testBug15946(): void
{
$this->checkExplicitMixed = false;
$this->checkNullables = true;
$this->analyse([__DIR__ . '/data/bug-15946.php'], []);
}

public function testFBound(): void
{
$this->checkNullables = true;
Expand Down
42 changes: 42 additions & 0 deletions tests/PHPStan/Rules/Functions/data/bug-15946.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php // lint >= 8.1

declare(strict_types = 1);

namespace Bug15946;

/**
* @param array<int, string>|array<string, string> $types
* @return array<int, string>|array<string, string>
*/
function copyTypes(array $types): array
{
$copy = [];
foreach ($types as $key => $type) {
$copy[$key] = $type;
}

return $copy;
}

enum ParameterType { case STRING; }
enum ArrayParameterType { case STRING; }

/**
* Like Doctrine\DBAL\Connection::expandArrayParameters()
*
* @param array<int<0, max>, string|ParameterType|ArrayParameterType>|array<string, string|ParameterType|ArrayParameterType> $types
* @return array<int<0, max>, string|ParameterType>|array<string, string|ParameterType>|null
*/
function nonArrayTypes(array $types): ?array
{
$nonArrayTypes = [];
foreach ($types as $key => $type) {
if ($type instanceof ArrayParameterType) {
return null;
}

$nonArrayTypes[$key] = $type;
}

return $nonArrayTypes;
}
141 changes: 108 additions & 33 deletions turbo-ext/src/ForeachHandler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -917,6 +917,15 @@ class ForeachHandler
if (UNEXPECTED(assigned.isUndef())) return zv::Val();
finalScope = std::move(assigned);
}
{
zv::Val condIterateeType = pt_expression_result_get_type(condResult.raw());
if (UNEXPECTED(condIterateeType.isUndef())) return zv::Val();
zv::Val condIterateeNativeType = pt_expression_result_get_native_type(condResult.raw());
if (UNEXPECTED(condIterateeNativeType.isUndef())) return zv::Val();
zv::Val memberEndScope = processByIterateeMember(nodeScopeResolver, stmt, parts, entryScope, originalStorage, context, condIterateeType.raw(), condIterateeNativeType.raw());
if (UNEXPECTED(memberEndScope.isUndef())) return zv::Val();
if (!memberEndScope.isNull()) finalScope = std::move(memberEndScope);
}

zv::Val bindingFlow;
{
Expand Down Expand Up @@ -1458,45 +1467,18 @@ class ForeachHandler
}

/* (twin addIterateeMemberConditionalHolders()) the key, the value and
* the iteratee tied together by the member of an iteratee union whose
* members' keys share no value; UNDEF = pending exception */
* the iteratee tied together by the member of the iteratee union;
* UNDEF = pending exception */
static zv::Val addIterateeMemberConditionalHolders(zval *scopeArg, zval *iteratee, zval *iterateeType, zend_string *keyVarName, zend_string *valueVarName)
{
zv::Val scope = zv::Val::copyOf(zv::Ref(scopeArg));
if (Z_TYPE_P(iterateeType) != IS_OBJECT || pt_ce_union_type == NULL || !instanceof_function(Z_OBJCE_P(iterateeType), pt_ce_union_type)
|| (pt_ce_benevolent_union_type != NULL && instanceof_function(Z_OBJCE_P(iterateeType), pt_ce_benevolent_union_type))) {
return scope;
}
bool error = false;
if (ptsh::isInstanceOf(iterateeType, PT_CLASS_TEMPLATE_TYPE, error)) return scope;
if (UNEXPECTED(error)) return zv::Val();
zv::Val members = pt_type_op(Z_OBJ_P(iterateeType), PT_OP_GET_TYPES, 0, NULL);
if (UNEXPECTED(members.isUndef())) return zv::Val();
if (ptlh::countOf(members.raw()) > PT_FEH_ITERATEE_MEMBERS_LIMIT) return scope;
zend_long tracked = pt_mutating_scope_has_expression_type(Z_OBJ_P(scope.raw()), iteratee);
if (UNEXPECTED(tracked < 0)) return zv::Val();
if (tracked != PT_TRI_YES) return scope;

zv::Val members;
if (UNEXPECTED(!getIterateeMembers(scope.raw(), iteratee, iterateeType, members))) return zv::Val();
if (members.isNull()) return scope;
std::vector<zv::Val> keyTypes;
for (auto entry : zv::ArrRef(members.raw())) {
zval *member = entry.value().deref().raw();
if (UNEXPECTED(Z_TYPE_P(member) != IS_OBJECT)) {
pt_throw_should_not_happen();
return zv::Val();
}
zend_long isArray = pt_type_op_trinary(Z_OBJ_P(member), PT_OP_IS_ARRAY, 0, NULL);
if (UNEXPECTED(isArray < 0)) return zv::Val();
if (isArray != PT_TRI_YES) return scope;
zend_long isConstantArray = pt_type_op_trinary(Z_OBJ_P(member), PT_OP_IS_CONSTANT_ARRAY, 0, NULL);
if (UNEXPECTED(isConstantArray < 0)) return zv::Val();
if (isConstantArray == PT_TRI_YES) return scope;
zv::Val keyType = typeOp(member, PT_OP_GET_ITERABLE_KEY_TYPE, "getIterableKeyType");
zv::Val keyType = typeOp(entry.value().deref().raw(), PT_OP_GET_ITERABLE_KEY_TYPE, "getIterableKeyType");
if (UNEXPECTED(keyType.isUndef())) return zv::Val();
for (zv::Val &otherKeyType : keyTypes) {
zend_long overlaps = isSuperTypeOf(otherKeyType.raw(), keyType.raw());
if (UNEXPECTED(overlaps < 0)) return zv::Val();
if (overlaps != PT_TRI_NO) return scope;
}
keyTypes.push_back(std::move(keyType));
}

Expand Down Expand Up @@ -1553,6 +1535,99 @@ class ForeachHandler
return scope;
}

/* (twin processByIterateeMember()) the scope after the loop joined from
* walking it over each member of the iteratee; null when the loop is not
* walked by member, UNDEF = pending exception */
zv::Val processByIterateeMember(zval *nodeScopeResolver, zval *stmt, StmtParts &parts, zval *entryScope, zval *storage, zval *context, zval *iterateeType, zval *iterateeNativeType) const
{
bool shouldConvergeLoops;
if (UNEXPECTED(!pt_statement_context_should_converge_loops(context, shouldConvergeLoops))) return zv::Val();
if (!shouldConvergeLoops) return zv::Val::null();
bool noDocComment;
if (UNEXPECTED(!hasNoDocComment(stmt, noDocComment))) return zv::Val();
if (!noDocComment || parts.valueVarName == NULL || parts.keyVarName == NULL || parts.byRef) return zv::Val::null();
zval *iteratee = parts.expr.raw();
zv::Val members;
if (UNEXPECTED(!getIterateeMembers(entryScope, iteratee, iterateeType, members))) return zv::Val();
if (members.isNull()) return zv::Val::null();

zv::Val endScope = zv::Val::null();
for (auto entry : zv::ArrRef(members.raw())) {
zval *member = entry.value().deref().raw();
// each walk converges with heads of its own, as its entry differs from the other walks'
zv::Val memberScope = pt_mutating_scope_specify_expression_type(Z_OBJ_P(entryScope), Z_OBJ_P(iteratee), member, iterateeNativeType, pt_trinary_singleton(PT_TRI_YES));
if (UNEXPECTED(memberScope.isUndef())) return zv::Val();
zv::Val memberStorage = pt_expression_result_storage_duplicate(storage);
if (UNEXPECTED(memberStorage.isUndef())) return zv::Val();
zv::Val noop = ptlh::newNoopNodeCallback();
if (UNEXPECTED(noop.isUndef())) return zv::Val();
zv::Val heads = pt_converged_loop_heads_new();
if (UNEXPECTED(heads.isUndef())) return zv::Val();
zv::Val memberContext = pt_statement_context_enter_loop_pass(context, heads.raw());
if (UNEXPECTED(memberContext.isUndef())) return zv::Val();
zv::Val memberResult = processStmt(nodeScopeResolver, stmt, memberScope.raw(), memberStorage.raw(), noop.raw(), memberContext.raw());
if (UNEXPECTED(memberResult.isUndef())) return zv::Val();
zv::Val hold;
zval *memberEndScope = pt_internal_statement_result_scope(memberResult.raw(), hold);
if (UNEXPECTED(memberEndScope == NULL)) return zv::Val();
if (endScope.isNull()) {
endScope = zv::Val::copyOf(zv::Ref(memberEndScope));
} else {
endScope = pt_mutating_scope_merge_with(Z_OBJ_P(endScope.raw()), memberEndScope);
if (UNEXPECTED(endScope.isUndef())) return zv::Val();
}
}

return endScope;
}

/* (twin getIterateeMembers()) the members of an iteratee union of general
* arrays whose keys share no value, into `out` (null when it is not such
* a union); false = pending exception */
[[nodiscard]] static bool getIterateeMembers(zval *scope, zval *iteratee, zval *iterateeType, zv::Val &out)
{
out = zv::Val::null();
if (Z_TYPE_P(iterateeType) != IS_OBJECT || pt_ce_union_type == NULL || !instanceof_function(Z_OBJCE_P(iterateeType), pt_ce_union_type)
|| (pt_ce_benevolent_union_type != NULL && instanceof_function(Z_OBJCE_P(iterateeType), pt_ce_benevolent_union_type))) {
return true;
}
bool error = false;
if (ptsh::isInstanceOf(iterateeType, PT_CLASS_TEMPLATE_TYPE, error)) return true;
if (UNEXPECTED(error)) return false;
zv::Val members = pt_type_op(Z_OBJ_P(iterateeType), PT_OP_GET_TYPES, 0, NULL);
if (UNEXPECTED(members.isUndef())) return false;
if (ptlh::countOf(members.raw()) > PT_FEH_ITERATEE_MEMBERS_LIMIT) return true;
zend_long tracked = pt_mutating_scope_has_expression_type(Z_OBJ_P(scope), iteratee);
if (UNEXPECTED(tracked < 0)) return false;
if (tracked != PT_TRI_YES) return true;

std::vector<zv::Val> keyTypes;
for (auto entry : zv::ArrRef(members.raw())) {
zval *member = entry.value().deref().raw();
if (UNEXPECTED(Z_TYPE_P(member) != IS_OBJECT)) {
pt_throw_should_not_happen();
return false;
}
zend_long isArray = pt_type_op_trinary(Z_OBJ_P(member), PT_OP_IS_ARRAY, 0, NULL);
if (UNEXPECTED(isArray < 0)) return false;
if (isArray != PT_TRI_YES) return true;
zend_long isConstantArray = pt_type_op_trinary(Z_OBJ_P(member), PT_OP_IS_CONSTANT_ARRAY, 0, NULL);
if (UNEXPECTED(isConstantArray < 0)) return false;
if (isConstantArray == PT_TRI_YES) return true;
zv::Val keyType = typeOp(member, PT_OP_GET_ITERABLE_KEY_TYPE, "getIterableKeyType");
if (UNEXPECTED(keyType.isUndef())) return false;
for (zv::Val &otherKeyType : keyTypes) {
zend_long overlaps = isSuperTypeOf(otherKeyType.raw(), keyType.raw());
if (UNEXPECTED(overlaps < 0)) return false;
if (overlaps != PT_TRI_NO) return true;
}
keyTypes.push_back(std::move(keyType));
}

out = std::move(members);
return true;
}

/* enterForeach()'s `foreach ($constantArray as $key => $value)` holders;
* UNDEF = pending exception */
static zv::Val addConstantArrayConditionalHolders(zval *scopeArg, StmtParts &parts, zval *constantArray)
Expand Down
Loading
Loading