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
29 changes: 16 additions & 13 deletions src/Analyser/MutatingScope.php
Original file line number Diff line number Diff line change
Expand Up @@ -5286,25 +5286,28 @@ private function generalizeType(Type $a, Type $b, int $depth): Type

$resultTypes[] = $resultArrayBuilder->getArray();
} else {
// Both inputs are sealed constant array shapes — their key
// sets are finite by construction. On the fall-through
// ArrayType path, recursing into `generalizeType` would
// widen e.g. `0|1` to `int<0, max>` — for both the keys and
// the values — losing the loop's per-iteration precision.
// Keep the literal union instead so the loop's bounds stay
// visible. (Scoped to sealed shapes so the general
// `generalize()` widening contract for legacy arrays — see
// ScopeTest::testGeneralize — is unaffected.)
$bothSealed = true;
// Neither input has unsealed extra keys, so their key sets
// are finite — the constant keys of the shapes. That holds
// for sealed shapes as well as for shapes of unknown
// sealedness (the only kind without bleeding edge). The
// latter report `isUnsealed()` as maybe and are deliberately
// let through: they carry no extra key type, so only
// `isUnsealed()->yes()` (an explicit `...<K, V>`) bails. On the
// fall-through ArrayType path, recursing into
// `generalizeType` would widen e.g. `0|1` to `int<0, max>`
// — for both the keys and the values — losing the loop's
// per-iteration precision. Keep the literal union instead
// so the loop's bounds stay visible.
$noneUnsealed = true;
foreach ([...$constantArrays['a'], ...$constantArrays['b']] as $constantArrayCheck) {
foreach ($constantArrayCheck->getConstantArrays() as $constantArrayInstance) {
if (!$constantArrayInstance->isSealed()->yes()) {
$bothSealed = false;
if ($constantArrayInstance->isUnsealed()->yes()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can one of the constant arrays be "maybe unsealed" at this point?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, a shape can be "maybe unsealed" at this point, and that is the case this fix is meant to let through.

ConstantArrayType::isUnsealed() (src/Type/Constant/ConstantArrayType.php:226) gives three results:

  • maybe when the shape has unknown sealedness ($this->unsealed === null). That is the legacy shape, and the only kind that exists without bleeding edge.
  • yes when the shape is definitely unsealed: it has extra keys, such as an explicit ...<K, V>.
  • no when the shape is sealed.

The old check, !isSealed()->yes(), also bailed on maybe, because isSealed() is just isUnsealed()->negate(). So every legacy shape was widened to int<0, max>, which is the bug reported in phpstan/phpstan#15749.

A maybe-unsealed shape has no extra key type, so its keys are only its constant keys and the set is finite, just like a sealed shape. Keeping the literal key union is safe for it. Only a definitely unsealed shape can hold keys outside that union, which is why the check now bails only on isUnsealed()->yes().

I added this explanation to the comment in MutatingScope::generalizeType() and to the same spot in the C++ mirror in turbo-ext/src/MutatingScope.cpp. Only comments changed, no behaviour. make tests (23,868 tests, 116 skipped) and make phpstan both pass. The change is in its own commit, 4dc2c6f, and has not been pushed.

$noneUnsealed = false;
break 2;
}
}
}
if ($bothSealed) {
if ($noneUnsealed) {
$resultKeyType = TypeCombinator::union($constantArraysA->getIterableKeyType(), $constantArraysB->getIterableKeyType());
$resultValueType = TypeCombinator::union($constantArraysA->getIterableValueType(), $constantArraysB->getIterableValueType());
if ($resultValueType->isOversizedArray()->yes()) {
Expand Down
32 changes: 32 additions & 0 deletions tests/PHPStan/Analyser/Bug15749Test.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php declare(strict_types = 1);

namespace PHPStan\Analyser;

use PHPStan\Testing\TypeInferenceTestCase;
use PHPUnit\Framework\Attributes\DataProvider;

/**
* Runs without bleeding edge, where constant array shapes have unknown sealedness.
*/
class Bug15749Test extends TypeInferenceTestCase
{

public static function dataAsserts(): iterable
{
yield from self::gatherAssertTypes(__DIR__ . '/data/bug-15749.php');
}

/**
* @param mixed ...$args
*/
#[DataProvider('dataAsserts')]
public function testAsserts(
string $assertType,
string $file,
...$args,
): void
{
$this->assertFileAsserts($assertType, $file, ...$args);
}

}
8 changes: 4 additions & 4 deletions tests/PHPStan/Analyser/ScopeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ public static function dataGeneralize(): array
{
// A directly constructed shape is a legacy (unsealed) one only while bleeding
// edge is off - the toggle is process-global, and PHPUnit 9 evaluates the
// provider after earlier test classes may have left it on. The widening
// contract below is the legacy one, so the inputs are pinned to it.
// provider after earlier test classes may have left it on. The inputs are
// pinned to legacy shapes, so the expectations below are for those.
return BleedingEdgeToggle::withBleedingEdge(false, static fn (): array => [
[
new ConstantStringType('a'),
Expand Down Expand Up @@ -147,7 +147,7 @@ public static function dataGeneralize(): array
new ConstantIntegerType(1),
new ConstantIntegerType(1),
]),
'non-empty-array<literal-string&lowercase-string&non-falsy-string, 1>',
'non-empty-array<\'a\'|\'b\', 1>',
],
[
new ConstantArrayType([
Expand All @@ -162,7 +162,7 @@ public static function dataGeneralize(): array
new ConstantIntegerType(1),
new ConstantIntegerType(2),
]),
'non-empty-array<literal-string&lowercase-string&non-falsy-string, int<1, max>>',
'non-empty-array<\'a\'|\'b\', 1|2>',
],
[
new UnionType([
Expand Down
85 changes: 85 additions & 0 deletions tests/PHPStan/Analyser/data/bug-15749.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?php declare(strict_types = 1);

namespace Bug15749;

use function PHPStan\Testing\assertType;

/** @return array<int<0, 3>, int> */
function foo(): array {
$a = [ ];
for ($i = 0; $i <= 3; $i++) {
$a[$i] = random_int(0, 100);
}
assertType('non-empty-array<int<0, 3>, int<0, 100>>', $a);
return $a;
}

function lessThan(): void {
$arr = [];
for ($i = 0; $i < 5; $i++) {
$arr[$i] = 'v';
}
assertType("non-empty-array<int<0, 4>, 'v'>", $arr);
}

function withCondition(): void {
$arr = [];
for ($i = 0; $i < 5; $i++) {
if (rand()) {
$arr[$i] = 'v';
}
}
assertType("array<int<0, 4>, 'v'>", $arr);
}

function existingKey(): void {
$arr = ['x' => 0];
for ($i = 0; $i < 5; $i++) {
$arr[$i] = $i;
}
assertType("non-empty-array<'x'|int<0, 4>, int<0, 4>>", $arr);
}

function whileLoop(): void {
$a = [];
$i = 0;
while ($i <= 3) {
$a[$i] = 1;
$i++;
}
assertType('non-empty-array<int<0, 3>, 1>', $a);
}

function foreachRange(): void {
$a = [];
foreach (range(0, 3) as $i) {
$a[$i] = 1;
}
assertType('array{1, 1, 1, 1}', $a);
}

function stringKeys(): void {
$a = [];
foreach (['a', 'b', 'c'] as $k) {
$a[$k] = 1;
}
assertType("array{a: 1, b: 1, c: 1}", $a);
}

function decrementing(): void {
$a = [];
for ($i = 3; $i >= 0; $i--) {
$a[$i] = 1;
}
assertType('non-empty-array<int<0, 3>, 1>', $a);
}

function nested(): void {
$a = [];
for ($i = 0; $i <= 2; $i++) {
for ($j = 0; $j <= 2; $j++) {
$a[$i][$j] = 1;
}
}
assertType('non-empty-array<int<0, 2>, non-empty-array<int<0, 2>, 1>>', $a);
}
23 changes: 12 additions & 11 deletions turbo-ext/src/MutatingScope.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9674,23 +9674,24 @@ class MutatingScope
if (UNEXPECTED(resultArray.isUndef())) return zv::Val();
resultTypes.push(std::move(resultArray));
} else {
/* Both inputs are sealed constant array shapes — see the
* twin's comment: keep the literal union instead of
* widening the keys and values */
bool bothSealed = true;
for (uint32_t side = 0; side < 2 && bothSealed; side++) {
/* Neither input has unsealed extra keys — see the twin's
* comment: keep the literal union instead of widening the
* keys and values. Shapes of unknown sealedness (isUnsealed
* maybe) are deliberately let through; only yes bails */
bool noneUnsealed = true;
for (uint32_t side = 0; side < 2 && noneUnsealed; side++) {
for (auto checkEntry : zv::TableRef(constantArrays.table((int) side))) {
zv::Val constantArrayInstances = pt_type_op(checkEntry.value().deref().asObject(), PT_OP_GET_CONSTANT_ARRAYS, 0, NULL);
if (UNEXPECTED(constantArrayInstances.isUndef() || Z_TYPE_P(constantArrayInstances.raw()) != IS_ARRAY)) return zv::Val();
for (auto instance : zv::TableRef(Z_ARRVAL_P(constantArrayInstances.raw()))) {
zend_long isSealed = pt_type_call_trinary(instance.value().deref().asObject(), PT_LC("issealed"), 0, NULL);
if (UNEXPECTED(isSealed < 0)) return zv::Val();
if (isSealed != PT_TRI_YES) {
bothSealed = false;
zend_long isUnsealed = pt_type_call_trinary(instance.value().deref().asObject(), PT_LC("isunsealed"), 0, NULL);
if (UNEXPECTED(isUnsealed < 0)) return zv::Val();
if (isUnsealed == PT_TRI_YES) {
noneUnsealed = false;
break;
}
}
if (!bothSealed) break;
if (!noneUnsealed) break;
}
}

Expand All @@ -9699,7 +9700,7 @@ class MutatingScope
zv::Val valueTypeB = pt_type_op(Z_OBJ_P(constantArraysB.raw()), PT_OP_GET_ITERABLE_VALUE_TYPE, 0, NULL);
if (UNEXPECTED(valueTypeB.isUndef())) return zv::Val();
zv::Val resultKeyType, resultValueType;
if (bothSealed) {
if (noneUnsealed) {
resultKeyType = unionTypes(keyTypeA.raw(), keyTypeB.raw());
if (UNEXPECTED(resultKeyType.isUndef())) return zv::Val();
resultValueType = unionTypes(valueTypeA.raw(), valueTypeB.raw());
Expand Down
Loading