Repository navigation
Know whether an array shape knows the order of its keys - #7279
Open
ondrejmirtes wants to merge 6 commits into
Open
ondrejmirtes wants to merge 6 commits into
ondrejmirtes wants to merge 6 commits into
Conversation
ondrejmirtes
force-pushed
the
array-shape-key-order
branch
10 times, most recently
from
December 2, 2026 20:34
497620a to
8e0ab07
Compare
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.
- ConstantArrayTypeBuilder::createEmpty() starts without a known key
order. Builders of literal arrays, lists, constant expressions and
functions that build arrays in a known order call makeKeyOrderKnown(),
createFromConstantArray() keeps the order knowledge of its source, and
functions that copy their input (array_filter(), array_column(),
array_replace(), array_merge(), ...) know the order only when their
inputs do.
- equals() compares unordered shapes by their key map, so two PHPDoc
shapes that differ only in key order are the same type.
- Two arrays whose keys come in different orders are never the same
array: isSuperTypeOf() and accepts() between shapes that know different
key orders answer No, and 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 of shapes in different orders, or of a shape that knows its
order with one that does not, 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.
- An intersection knows its key order only when one of the shapes that
knows its order lists every key of it.
- 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}>.
- Loop widening keeps the key order of two shapes that list the same keys
in the same order, and forgets it otherwise.
turbo-ext: the same in the shadowed classes.
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
…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, spreading and taking a column of 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. A shape with only integer keys renumbered by position knows its key order again, so array_merge(), array_combine() and unpacking of such shapes keep it. turbo-ext: the same in ConstantArrayType and InitializerExprTypeResolver. 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. turbo-ext: the same in CountNarrowingHelper. 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. Likewise, values appended to a builder
in no known order make a list only maybe.
turbo-ext: the same in ConstantArrayType, ConstantArrayTypeBuilder and
LateResolvableArrayShapeType.
Amp-Thread-ID: https://ampcode.com/threads/T-01a230f4-34d7-76c1-abde-c90173e47a85
…e key order is known turbo-ext: the same in ConstantArrayType. Amp-Thread-ID: https://ampcode.com/threads/T-01a230f4-34d7-76c1-abde-c90173e47a85
ondrejmirtes
force-pushed
the
array-shape-key-order
branch
from
December 3, 2026 09:42
8e0ab07 to
067ff00
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
ConstantArrayTypestands 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 toConstantArrayTypeinstead of a subclass or an accessory type: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.TemplateTypeHelper::generalizeInferredTemplateType). This fixes the invariantBox<array{t: string, a: int}>vsBox<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 absorbsarray{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 isbool, never constanttrue. Literal arrays with different key orders stayfalse.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()andgetLastIterableValueType()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()andarray_shift()use them again, soarray_key_first(['a' => 1, 'b' => 2])is'a'whilearray_key_first($phpDocShape)stays'a'|'b'. For a list,array_key_first()is0.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 (likemakeUnsealed()),createFromConstantArray()inherits it. Literal arrays, constant values, PHPDoc constant expressions, lists (explode(),range(),preg_split(),sscanf(),array_fill(), enumcases()), 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, soarray_column($phpDocShapeOfRows, 'id')isarray{1|2, 1|2}, notarray{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.foreachunrolling 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.TypeCombinatorTestmarks 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()andarray_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, whilearray{0: int, 2: string}never is).array{int, string},list{0: int, 1?: string}andarray{0: int, 1: string}&liststay lists, with their keys in ascending order, and a list that has to name its keys describes itself aslist{...}. 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}withcount() === 1isarray{a: int}).turbo-ext: the same in
ConstantArrayType,ConstantArrayTypeBuilder,TemplateConstantArrayType,LateResolvableArrayShapeType,TemplateTypeHelper,InitializerExprTypeResolver,CountNarrowingHelper,UnionType,IntersectionType,StaticType,ConstantArrayTypeBuilder,ArrayType,MutatingScope,FuncCallScopeEffectsHelper,PhpClassReflectionExtension,ConstantTypeHelperand the late-resolvable trait.Supersedes #7274.
Closes phpstan/phpstan#15908
Closes phpstan/phpstan#11600
Closes phpstan/phpstan#15679