Skip to content

Keep the literal key/value union when generalizing constant array shapes of unknown sealedness in loops - #7095

Merged
VincentLanglet merged 3 commits into
phpstan:2.3.xfrom
phpstan-bot:create-pull-request/patch-cf8hs97
Nov 17, 2026
Merged

VincentLanglet merged 3 commits into
phpstan:2.3.xfrom
phpstan-bot:create-pull-request/patch-cf8hs97

Conversation

@phpstan-bot

Copy link
Copy Markdown
Collaborator

Summary

Without bleeding edge, an array filled in a bounded loop lost its key bound:

$a = [];
for ($i = 0; $i <= 3; $i++) {
    $a[$i] = random_int(0, 100);
}
// was: non-empty-array<int<0, max>, int<0, 100>>, now: non-empty-array<int<0, 3>, int<0, 100>>

With bleeding edge the result was already precise. This change gives the same result without it.

Changes

  • src/Analyser/MutatingScope.php (generalizeType()): when two constant array shapes with different key sets are merged into a general ArrayType, keep the literal key/value union unless a shape is definitely unsealed (isUnsealed()->yes()). Before, this needed isSealed()->yes().
  • turbo-ext/src/MutatingScope.cpp: same change in the native mirror. It was checked by reverting only the PHP side and running the new test with the extension loaded (it passes), and tests/smoke.php prints ALL OK.
  • tests/PHPStan/Analyser/ScopeTest.php: the legacy-shape rows of testGeneralize now give the same result as sealed shapes. For example, array{a: 1} + array{a: 1, b: 2} gives non-empty-array<'a'|'b', 1|2> instead of non-empty-array<literal-string&lowercase-string&non-falsy-string, int<1, max>>.

Analogous cases probed (all run without bleeding edge):

  • Fixed by this change: for with <, decrementing for, conditional assignment in the body, an array that starts with a string key, nested loops, and while loops.
  • Already precise: foreach over range() and over constant string lists.
  • Not fixed: do-while gives int<0, max> both with and without bleeding edge, and also in 2.1.x. The body runs before the condition narrows the counter, so this is a separate limitation. It is not covered here.

Root cause

Since 2.2, $a[0|1] = … on array{}|array{0: …} produces the shape array{0?: …, 1?: …} instead of the general array<0|1, …>. The loop fixed point therefore takes the constant-array branch of generalizeType(). That branch keeps the literal key union only for sealed shapes and widened 0 + 0|1 to int<0, max> for anything else. Without bleeding edge every shape has unknown sealedness, so the bound was always lost. A shape of unknown sealedness has no extra key type, so its key set is finite (its constant keys), the same as a sealed shape. Only definitely unsealed shapes (...<K, V>) need the widening. Termination still holds: it relies on the counter's own generalization and the shape size limit, as on the sealed path. The issue says "since 2.3.6", but the regression actually appears in released PHARs from 2.2.0 on; 2.1.40 was precise.

Test

  • New tests/PHPStan/Analyser/LegacyArrayShapeTypeInferenceTest.php with tests/PHPStan/Analyser/data/bug-15749.php. It is a TypeInferenceTestCase without bleeding edge, because the nsrt tests always enable it and so could not catch this. It has the issue's reproducer verbatim plus the probes listed above: 7 of its 9 assertions fail without the fix.
  • ScopeTest::testGeneralize expectations updated as described above.
  • Full test suite, make phpstan, and make cs-fix pass. make name-collision aborts on a parse error in an unrelated existing file (readonly-property-assign-clone-with.php, PHP 8.5 syntax); the new namespace Bug15749 is unique.
  • All 102 tests/bench/data files analysed without bleeding edge produce identical output and timing before and after the change.

Fixes phpstan/phpstan#15749

…pes of unknown sealedness in loops

- MutatingScope::generalizeType(): when two constant array shapes with
  different key sets are merged into a general ArrayType, keep the
  union of their keys and values unless a shape is definitely unsealed
  (`isUnsealed()->yes()`). Previously this required `isSealed()->yes()`,
  which only holds with bleeding edge. Without it, every shape has
  unknown sealedness, so loop-built arrays like
  `for ($i = 0; $i <= 3; $i++) { $a[$i] = ...; }` widened their keys to
  `int<0, max>`. Since 2.2 `$a[0|1] = ...` produces the shape
  `array{0?: ..., 1?: ...}` instead of `array<0|1, ...>`, so the
  constant-array path is taken where the general-array path used to keep
  the bound.
- Port the same condition to the native mirror in
  turbo-ext/src/MutatingScope.cpp.
- ScopeTest::testGeneralize: legacy shapes now generalize like sealed
  ones (`non-empty-array<'a'|'b', 1|2>` instead of widening to
  `literal-string` / `int<1, max>`).
- New LegacyArrayShapeTypeInferenceTest runs without bleeding edge and
  covers for (<=, <, decrementing, conditional assignment, pre-existing
  string key, nested) and while loops. foreach over constant arrays was
  already precise. do-while stays at int<0, max> with and without
  bleeding edge: its body never sees the narrowed counter, so that is a
  separate limitation.
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.

…sealed check

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
/**
* Runs without bleeding edge, where constant array shapes have unknown sealedness.
*/
class LegacyArrayShapeTypeInferenceTest extends TypeInferenceTestCase

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.

rename this class to Bug15749Test

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.

I renamed the test class from LegacyArrayShapeTypeInferenceTest to Bug15749Test, and the file to tests/PHPStan/Analyser/Bug15749Test.php. Nothing else in the repo referred to the old name. The class still runs without bleeding edge and uses the same data file, tests/PHPStan/Analyser/data/bug-15749.php.

make tests passes (23,868 tests, 116 skipped), and make phpstan reports no errors. The rename is in its own commit, c110df0, and has not been pushed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@VincentLanglet
VincentLanglet merged commit 0d2c43a into phpstan:2.3.x Nov 17, 2026
904 of 909 checks passed
@VincentLanglet
VincentLanglet deleted the create-pull-request/patch-cf8hs97 branch November 17, 2026 10:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

less precise array key inferring since 2.3.6

3 participants