Repository navigation
Know whether an array shape knows the order of its keys - #7279
Open
ondrejmirtes wants to merge 12 commits into
Open
ondrejmirtes wants to merge 12 commits into
ondrejmirtes wants to merge 12 commits into
Conversation
ondrejmirtes
force-pushed
the
array-shape-key-order
branch
5 times, most recently
from
December 2, 2026 15:50
c61af31 to
979f41a
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: 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
force-pushed
the
array-shape-key-order
branch
3 times, most recently
from
December 2, 2026 17:49
62a6b9a to
56aabc9
Compare
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
…e key order is known Amp-Thread-ID: https://ampcode.com/threads/T-01a230f4-34d7-76c1-abde-c90173e47a85
ondrejmirtes
force-pushed
the
array-shape-key-order
branch
from
December 2, 2026 19:48
56aabc9 to
497620a
Compare
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
force-pushed
the
array-shape-key-order
branch
from
December 2, 2026 20:34
497620a to
8e0ab07
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