Skip to content

Know whether an array shape knows the order of its keys - #7279

Open
ondrejmirtes wants to merge 12 commits into
2.3.xfrom
array-shape-key-order
Open

ondrejmirtes wants to merge 12 commits into
2.3.xfrom
array-shape-key-order

Conversation

@ondrejmirtes

@ondrejmirtes ondrejmirtes commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

ConstantArrayType stands both for literal arrays, whose key order is known (['a', 'b'] === ['b', 'a'] is always false), and for array shapes written in PHPDoc, which only say which keys are present. This adds a key-order flag to ConstantArrayType instead of a subclass or an accessory type:

  • PHPDoc shapes with explicit keys (LateResolvableArrayShapeType) are built without a known order. Literal arrays, lists, and shapes with fewer than two keys know their order (isKeyOrderKnown()).
  • equals() compares unordered shapes by their key map.
  • Template inference for non-covariant templates forgets the key order of the inferred shapes (TemplateTypeHelper::generalizeInferredTemplateType). This fixes the invariant Box<array{t: string, a: int}> vs Box<array{a: int, t: string}> case without bleeding edge.
  • isSuperTypeOf() / accepts(): an unordered shape covers every order of its keys (Yes). An ordered shape against an unordered one with the same keys is Maybe. Two shapes that both know their order and list their shared keys in different orders are No, so ['a' => 1, 'b' => 2] and ['b' => 2, 'a' => 1] are no longer supertypes of each other (Union of two literal arrays with the same keys in a different order keeps only one key order phpstan#15679).
  • TypeCombinator::union() of an ordered shape and an unordered one with the same keys is unordered: when the unordered one holds the ordered one, it is the result; when the ordered one has the wider values, it holds the other once it forgets its key order (array{start: mixed, ...} from code absorbs array{start: float, ...} from PHPDoc, as before this PR). intersect() keeps the ordered one. remove() of an ordered shape from an unordered one leaves the unordered shape.
  • === between shapes where either side's order is unknown is compared key by key and is bool, never constant true. Literal arrays with different key orders stay false.
  • The order is kept by recreate(), the builder and the combinator rules. The (unordered) marker appears only in the cache description, so error messages do not change.

Code that depends on the order now uses the flag:

  • getFirstIterableKeyType(), getLastIterableKeyType(), getFirstIterableValueType() and getLastIterableValueType() are no longer deprecated (add array_first and array_last return type extensions #4499 deprecated them because PHPDoc shapes do not enforce the order). An array that knows its key order answers with its first or last key or value, an unordered one with the union. array_key_first(), array_key_last(), array_first(), array_last(), reset(), end(), array_pop() and array_shift() use them again, so array_key_first(['a' => 1, 'b' => 2]) is 'a' while array_key_first($phpDocShape) stays 'a'|'b'. For a list, array_key_first() is 0.
  • array_search() (searchArray()) stops at the first key that surely matches when the key order is known: array_search(1, ['a' => 1, 'b' => 1]) is 'a'. An unordered shape still answers with every matching key.
  • ConstantArrayTypeBuilder::createEmpty() starts without a known key order; makeKeyOrderKnown() turns it on (like makeUnsealed()), createFromConstantArray() inherits it. Literal arrays, constant values, PHPDoc constant expressions, lists (explode(), range(), preg_split(), sscanf(), array_fill(), enum cases()), regex matches, compact(), array_combine() and rebuilt intersections mark the order known; array_filter(), array_column(), array_replace(), array_unshift() and the general-array intersection keep the order of their source, so array_column($phpDocShapeOfRows, 'id') is array{1|2, 1|2}, not array{1, 2}. With bleeding edge, values appended in no known order make a list only maybe. get_defined_vars() no longer claims an order (PHP orders variables by first mention, which the scope does not track). Loop widening keeps the order of two shapes listing the same keys in the same order (ConstantArrayType::getKeyTypesInMergedOrderWith()), and forgets it otherwise.
  • foreach unrolling is unchanged: shapes are unrolled by key in their written order, as before.

Merging shapes (TypeCombinator::union() generalization, joins of branches, SharedKeyShapeWidening) keeps an interleaved key order when both shapes list their shared keys in the same order, and forgets the order otherwise, so literal arrays with the same keys in different orders merge into one unordered shape. Intersections take the order of the first shape that knows it. TypeCombinatorTest marks unordered shapes with (unordered) and covers these merges.

Positional operations answer without a key order for unordered shapes (phpstan/phpstan#11600): getKeysArray() / getValuesArray() put any key or value (and the unsealed extras) at every position; array_pop() / array_shift() make every key optional; array_slice(), array_reverse(), array_splice() and array_chunk() without preserved keys, implode(), array_combine(), array_merge() and array spread no longer assume the written order. Literal arrays and lists keep their exact answers.

With bleeding edge, a PHPDoc shape with explicit keys is no longer a list: array{0: int, 1: string} only says the keys 0 and 1 are present, so it is a list only maybe, decided as if its keys came sorted (array{1: string, 0: int} too, while array{0: int, 2: string} never is). array{int, string}, list{0: int, 1?: string} and array{0: int, 1: string}&list stay lists, with their keys in ascending order, and a list that has to name its keys describes itself as list{...}. Without bleeding edge nothing changes here.

To keep count() narrowing for such shapes, it now narrows every sealed shape that is not a list: a count equal to the number of required keys drops the optional ones, and a count equal to the number of all keys makes every key present (array{a: int, b?: string} with count() === 1 is array{a: int}).

turbo-ext: the same in ConstantArrayType, ConstantArrayTypeBuilder, TemplateConstantArrayType, LateResolvableArrayShapeType, TemplateTypeHelper, InitializerExprTypeResolver, CountNarrowingHelper, UnionType, IntersectionType, StaticType, ConstantArrayTypeBuilder, ArrayType, MutatingScope, FuncCallScopeEffectsHelper, PhpClassReflectionExtension, ConstantTypeHelper and the late-resolvable trait.

Supersedes #7274.

Closes phpstan/phpstan#15908
Closes phpstan/phpstan#11600
Closes phpstan/phpstan#15679

@ondrejmirtes
ondrejmirtes force-pushed the array-shape-key-order branch 5 times, most recently from c61af31 to 979f41a Compare December 2, 2026 15:50
ConstantArrayType stands both for literal arrays, whose key order is
known, and for array shapes written in PHPDoc, which only list the keys
that are present. It now carries a key-order flag: PHPDoc shapes with
explicit keys are built without a known order, and literal arrays keep it.

- equals() compares unordered shapes by their key map, so two PHPDoc
  shapes that differ only in key order are the same type.
- Template inference for non-covariant templates forgets the key order of
  the inferred shapes, so Box<array{t: string, a: int}> is accepted for
  Box<array{a: int, t: string}>.
- isSuperTypeOf() and accepts() answer Maybe when an ordered shape meets
  one with the same keys whose order is unknown.
- === between shapes whose order is unknown is bool, not always false.
- A union with an unordered shape is unordered; an intersection keeps
  the known order.

turbo-ext: the same in ConstantArrayType, ConstantArrayTypeBuilder,
TemplateConstantArrayType, LateResolvableArrayShapeType,
TemplateTypeHelper and InitializerExprTypeResolver.

Amp-Thread-ID: https://ampcode.com/threads/T-01a230f4-34d7-76c1-abde-c90173e47a85
Loose comparison of PHPDoc shapes reaches the key-by-key branch even
when the shapes cannot be equal, so it now has tests for a missing key
after a value that may be equal, and for differing values. Mutation
testing reported the branch's early return as uncovered.

turbo-ext: the same toBoolean() in InitializerExprTypeResolver.cpp.

Amp-Thread-ID: https://ampcode.com/threads/T-01a230f4-34d7-76c1-abde-c90173e47a85
A shape whose isList is Maybe might hold 0 and 1 in the other order, so
it knows its key order only when its flag says so. The new tests cover
that, and accepts() no longer asks isConstantArray() before
getConstantArrays(), which already returns nothing for other types.

turbo-ext: the same in ConstantArrayType.cpp.

Amp-Thread-ID: https://ampcode.com/threads/T-01a230f4-34d7-76c1-abde-c90173e47a85
getFirstIterableKeyType(), getLastIterableKeyType(),
getFirstIterableValueType() and getLastIterableValueType() were
deprecated because array shapes from PHPDoc do not say in which order
their keys come. ConstantArrayType now answers them with the union of
its keys or values when it does not know its key order, and with the
first or last ones when it does, so they are no longer deprecated.

array_key_first(), array_key_last(), array_first(), array_last(),
reset(), end(), array_pop() and array_shift() use them again, and
UnionType, IntersectionType, StaticType and late-resolvable types
delegate to them instead of to getIterableKeyType() and
getIterableValueType().

turbo-ext: the same in ConstantArrayType, UnionType, IntersectionType,
StaticType and the late-resolvable trait.

Amp-Thread-ID: https://ampcode.com/threads/T-01a230f4-34d7-76c1-abde-c90173e47a85
… and array_last()

The test runs only on PHP 8.5+, so the previous commit missed it.

Amp-Thread-ID: https://ampcode.com/threads/T-01a230f4-34d7-76c1-abde-c90173e47a85
A literal array and a PHPDoc shape with the same keys stayed apart in a
union when the literal had the wider values, because a shape whose key
order is known does not hold every order of the other one. The union is now
the literal shape with its key order forgotten.

Amp-Thread-ID: https://ampcode.com/threads/T-01a230f4-34d7-76c1-abde-c90173e47a85
@ondrejmirtes
ondrejmirtes force-pushed the array-shape-key-order branch 3 times, most recently from 62a6b9a to 56aabc9 Compare December 2, 2026 17:49
Two arrays whose keys come in different orders are never the same array,
so isSuperTypeOf() and accepts() between shapes that know different key
orders answer No, and a union of them merges into a shape that does not
know its key order, and is not a list unless both are.

A merge of shapes that list their shared keys in one order keeps the keys
only one of them has where that one lists them, instead of after all the
others. An intersection knows its key order only when one of the shapes
that knows its order lists every key of it.

Amp-Thread-ID: https://ampcode.com/threads/T-01a230f4-34d7-76c1-abde-c90173e47a85
…t do not know it

A PHPDoc array shape lists the keys that are present, not the order in
which they come. Popping, shifting, slicing, reversing, splicing,
chunking, taking the keys or values, imploding, combining, merging and
spreading such a shape no longer assume the written order: every
position can hold any of its keys, or any of its extras when the shape
is unsealed. Literal arrays and lists keep their exact answers.

Amp-Thread-ID: https://ampcode.com/threads/T-01a230f4-34d7-76c1-abde-c90173e47a85
A count equal to the number of required keys rules out every optional
key, and a count equal to the number of all keys makes every one of
them present, whatever the keys and in whatever order they come.

Amp-Thread-ID: https://ampcode.com/threads/T-01a230f4-34d7-76c1-abde-c90173e47a85
…edge

array{0: int, 1: string} says that the keys 0 and 1 are present, not
that they come in this order, so [1 => 'a', 0 => 1] fits it too. With
bleeding edge such a shape is a list only maybe, when its keys sorted
could form one, and a list that has to name its keys describes itself
as list{...}. list{...} and array{...}&list keep being lists, with
their keys in ascending order.

Amp-Thread-ID: https://ampcode.com/threads/T-01a230f4-34d7-76c1-abde-c90173e47a85
@ondrejmirtes
ondrejmirtes force-pushed the array-shape-key-order branch from 56aabc9 to 497620a Compare December 2, 2026 19:48
ConstantArrayTypeBuilder::createEmpty() no longer claims that the keys come in
the order they are set. Builders of literal arrays, lists and arrays copied
from a source that knows its order call makeKeyOrderKnown(), and
createFromConstantArray() keeps the order knowledge of its source. With
bleeding edge, values appended in no known order make a list only maybe.

Loop widening keeps the key order of two shapes that list the same keys in
the same order, and forgets it otherwise.

Amp-Thread-ID: https://ampcode.com/threads/T-01a230f4-34d7-76c1-abde-c90173e47a85
@ondrejmirtes
ondrejmirtes force-pushed the array-shape-key-order branch from 497620a to 8e0ab07 Compare December 2, 2026 20:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant