Skip to content
Open
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
43 changes: 40 additions & 3 deletions src/Analyser/ExprHandler/Helper/CountNarrowingHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -135,9 +135,15 @@ public function specifyCountSize(
continue;
}

$resultTypes[] = $isList->yes()
? $arrayType->truncateListToSize($sizeType)
: TypeCombinator::intersect($arrayType, new NonEmptyArrayType());
if ($isList->yes()) {
$resultTypes[] = $arrayType->truncateListToSize($sizeType);
continue;
}

foreach ($arrayType->getConstantArrays() as $constantArray) {
$arrayType = $this->narrowShapeToSize($constantArray, $sizeType);
}
$resultTypes[] = TypeCombinator::intersect($arrayType, new NonEmptyArrayType());
}

if ($context->truthy() && $isConstantArray->yes() && $isList->yes()) {
Expand Down Expand Up @@ -180,4 +186,35 @@ public function specifyCountSize(
return $this->defaultNarrowingHelper->createForSubject($countFuncCall->getArgs()[0]->value, TypeCombinator::union(...$resultTypes), $context, $scope)->setRootExpr($rootExpr);
}

/**
* A sealed shape whose size can only be the number of its required keys has none of the optional ones,
* and one whose size can only be the number of all its keys has every one of them.
*/
private function narrowShapeToSize(ConstantArrayType $arrayType, Type $sizeType): Type
{
$optionalKeys = $arrayType->getOptionalKeys();
if ($optionalKeys === [] || !$arrayType->isUnsealed()->no()) {
return $arrayType;
}

$keyTypes = $arrayType->getKeyTypes();
$sizeType = TypeCombinator::intersect($sizeType, $arrayType->getArraySize());
if ((new ConstantIntegerType(count($keyTypes) - count($optionalKeys)))->isSuperTypeOf($sizeType)->yes()) {
$narrowed = $arrayType;
foreach ($optionalKeys as $i) {
$narrowed = $narrowed->unsetOffset($keyTypes[$i]);
}

return $narrowed;
}

if ((new ConstantIntegerType(count($keyTypes)))->isSuperTypeOf($sizeType)->yes()) {
foreach ($optionalKeys as $i) {
$arrayType = $arrayType->makeOffsetRequired($keyTypes[$i]);
}
}

return $arrayType;
}

}
12 changes: 11 additions & 1 deletion src/Analyser/ExprHandler/Helper/FuncCallScopeEffectsHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -433,7 +433,14 @@ private function getArrayFunctionAppendingType(FunctionReflection $functionRefle
$newArrayTypes = [];
$prepend = $functionReflection->getName() === 'array_unshift';
foreach ($constantArrays as $constantArray) {
$arrayTypeBuilder = $prepend ? ConstantArrayTypeBuilder::createEmpty() : ConstantArrayTypeBuilder::createFromConstantArray($constantArray);
if ($prepend) {
$arrayTypeBuilder = ConstantArrayTypeBuilder::createEmpty();
if ($constantArray->isKeyOrderKnown()) {
$arrayTypeBuilder->makeKeyOrderKnown();
}
} else {
$arrayTypeBuilder = ConstantArrayTypeBuilder::createFromConstantArray($constantArray);
}

$setOffsetValueTypes(
$scope,
Expand Down Expand Up @@ -490,6 +497,9 @@ static function (?Type $offsetType, Type $valueType, bool $optional) use (&$arra
// unpack value type" and are now subsumed by the
// unsealed slot).
$builder = ConstantArrayTypeBuilder::createEmpty();
if ($constantArrays[0]->isKeyOrderKnown()) {
$builder->makeKeyOrderKnown();
}
$intValues = [];
foreach ($constantArrays[0]->getKeyTypes() as $i => $keyType) {
$valueType = $constantArrays[0]->getValueTypes()[$i];
Expand Down
21 changes: 20 additions & 1 deletion src/Analyser/MutatingScope.php
Original file line number Diff line number Diff line change
Expand Up @@ -6620,7 +6620,26 @@ private function generalizeConstantFloats(array $a, array $b, float $entryMin, f
private function generalizeShapesKeyByKey(Type $a, Type $b, int $depth, Type $allA, Type $allB): Type
{
$resultArrayBuilder = ConstantArrayTypeBuilder::createEmpty();
foreach (TypeUtils::flattenTypes(TypeCombinator::union($a->getIterableKeyType(), $b->getIterableKeyType())) as $keyType) {
$keyTypes = TypeUtils::flattenTypes(TypeCombinator::union($a->getIterableKeyType(), $b->getIterableKeyType()));

// the shape keeps the key order of the two shapes it widens when they list the same keys in it; keys
// only one of them lists can be added in any order by the passes of a loop
$aShapes = $a->getConstantArrays();
$bShapes = $b->getConstantArrays();
if (count($aShapes) === 1 && count($bShapes) === 1) {
$mergedKeyTypes = $aShapes[0]->getKeyTypesInMergedOrderWith($bShapes[0]);
if (
$mergedKeyTypes !== null
&& count($mergedKeyTypes) === count($keyTypes)
&& count($mergedKeyTypes) === count($aShapes[0]->getKeyTypes())
&& count($mergedKeyTypes) === count($bShapes[0]->getKeyTypes())
) {
$keyTypes = $mergedKeyTypes;
$resultArrayBuilder->makeKeyOrderKnown();
}
}

foreach ($keyTypes as $keyType) {
$aHasOffset = $a->hasOffsetValueType($keyType);
$bHasOffset = $b->hasOffsetValueType($keyType);
$optional = !$aHasOffset->and($bHasOffset)->negate()->no();
Expand Down
1 change: 1 addition & 0 deletions src/PhpDoc/ConstExprNodeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ public function resolve(ConstExprNode $node, NameScope $nameScope): Type
private function resolveArrayNode(ConstExprArrayNode $node, NameScope $nameScope): Type
{
$arrayBuilder = ConstantArrayTypeBuilder::createEmpty();
$arrayBuilder->makeKeyOrderKnown();
foreach ($node->items as $item) {
if ($item->key === null) {
$key = null;
Expand Down
43 changes: 43 additions & 0 deletions src/Reflection/InitializerExprTypeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -553,6 +553,7 @@ public function getArrayType(Expr\Array_ $expr, callable $getTypeCallback, ?PhpV
}

$arrayBuilder = ConstantArrayTypeBuilder::createEmpty();
$arrayBuilder->makeKeyOrderKnown();
$isList = null;
$hasOffsetValueTypes = [];
foreach ($expr->items as $arrayItem) {
Expand All @@ -571,6 +572,11 @@ public function getArrayType(Expr\Array_ $expr, callable $getTypeCallback, ?PhpV
$slotOrder = [];

foreach ($constantArrays as $constantArrayType) {
// the integer keys are renumbered in the order the array has them
$constantArrayType = $constantArrayType->inRenumberingOrder();
if (!$constantArrayType->isKeyOrderKnown()) {
$arrayBuilder->forgetKeyOrder();
}
$nextIntegerSlot = 0;
foreach ($constantArrayType->getKeyTypes() as $i => $keyType) {
if ($keepStringKeys && $keyType->isString()->yes()) {
Expand Down Expand Up @@ -1401,6 +1407,43 @@ private function resolveConstantArrayTypeComparison(ConstantArrayType $leftType,
$leftValueTypes = $leftType->getValueTypes();
$rightValueTypes = $rightType->getValueTypes();

if (!$leftType->isKeyOrderKnown() || !$rightType->isKeyOrderKnown()) {
// a shape that does not know its key order is compared key by key,
// and it is never certainly identical to another array
$rightKeyIndexes = [];
foreach ($rightKeyTypes as $j => $rightKeyType) {
$rightKeyIndexes[$rightKeyType->getValue()] = $j;
}

foreach ($leftKeyTypes as $i => $leftKeyType) {
$j = $rightKeyIndexes[$leftKeyType->getValue()] ?? null;
if ($j === null) {
if (!$leftType->isOptionalKey($i)) {
return new TypeResult(new ConstantBooleanType(false), []);
}
continue;
}

unset($rightKeyIndexes[$leftKeyType->getValue()]);
if ($leftType->isOptionalKey($i) && $rightType->isOptionalKey($j)) {
continue;
}

$leftIdenticalToRightResult = $valueComparisonCallback($leftValueTypes[$i], $rightValueTypes[$j]);
if ($leftIdenticalToRightResult->type->toBoolean()->isFalse()->yes()) {
return $leftIdenticalToRightResult;
}
}

foreach ($rightKeyIndexes as $j) {
if (!$rightType->isOptionalKey($j)) {
return new TypeResult(new ConstantBooleanType(false), []);
}
}

return new TypeResult(new BooleanType(), []);
}

$resultType = new ConstantBooleanType(true);

foreach ($leftKeyTypes as $i => $leftKeyType) {
Expand Down
1 change: 1 addition & 0 deletions src/Reflection/Php/PhpClassReflectionExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -640,6 +640,7 @@ private function createMethod(
&& strtolower($methodReflection->getName()) === 'cases'
) {
$arrayBuilder = ConstantArrayTypeBuilder::createEmpty();
$arrayBuilder->makeKeyOrderKnown();
foreach (array_keys($classReflection->getEnumCases()) as $name) {
$arrayBuilder->setOffsetValueType(null, new EnumCaseObjectType($classReflection->getName(), $name));
}
Expand Down
64 changes: 58 additions & 6 deletions src/Type/ArrayAlgebra.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use PHPStan\Type\Generic\ArrayKeyTemplateHelper;
use PHPStan\Type\Generic\TemplateType;
use function array_key_exists;
use function array_map;
use function array_merge;
use function count;
use function get_class;
Expand Down Expand Up @@ -105,6 +106,7 @@ public static function splitConstantArrayAtFiniteValue(ConstantArrayType $array)
$array->getOptionalKeys(),
$array->isList(),
$array->getUnsealedTypes(),
$array->isKeyOrderKnown(),
);
}

Expand Down Expand Up @@ -283,6 +285,7 @@ private static function tryIntersectShapeWithArray(ConstantArrayType $constArray
}

$newArray = ConstantArrayTypeBuilder::createEmpty();
$newArray->makeKeyOrderKnown();
// Preserve unsealed extras from the source shape so the
// rebuild doesn't silently turn `array{k: int, ...} & X`
// into a sealed `array{k: int}` — intersect with the other
Expand Down Expand Up @@ -326,7 +329,7 @@ private static function tryIntersectShapeWithArray(ConstantArrayType $constArray
$newArray->setOffsetValueType($keyType, $otherValueTypes[$k], $otherConstantArray->isOptionalKey($k));
}
}
$newArrayType = $newArray->getArray();
$newArrayType = self::inKeyOrderOf($newArray->getArray(), $constArray, ...($otherConstantArray !== null ? [$otherConstantArray] : []));
if ($constArray->isList()->yes()) {
$newArrayType = TypeCombinator::intersect($newArrayType, new AccessoryArrayListType());
}
Expand Down Expand Up @@ -365,6 +368,7 @@ private static function intersectDefiniteConstantArrays(ConstantArrayType $a, Co
}

$newArray = ConstantArrayTypeBuilder::createEmpty();
$newArray->makeKeyOrderKnown();

if ($bothUnsealed) {
[$unsealedKey, $unsealedValue] = ArrayKeyTemplateHelper::intersectEntryTypes($aUnsealed, $bUnsealed);
Expand Down Expand Up @@ -449,7 +453,7 @@ private static function intersectDefiniteConstantArrays(ConstantArrayType $a, Co
$newArray->setOffsetValueType($keyType, $value, $optional);
}

$newArrayType = $newArray->getArray();
$newArrayType = self::inKeyOrderOf($newArray->getArray(), $a, $b);
// optional keys rebuilt one by one may each be left out alone, so the
// builder cannot tell a list from the keys - the inputs can
if ($a->isList()->yes() || $b->isList()->yes()) {
Expand All @@ -459,6 +463,22 @@ private static function intersectDefiniteConstantArrays(ConstantArrayType $a, Co
return $newArrayType;
}

/**
* The intersection of shapes built key by key, with its keys in the order of a shape
* that knows it and lists them all.
*/
private static function inKeyOrderOf(Type $intersection, ConstantArrayType ...$shapes): Type
{
if (!$intersection->isConstantArray()->yes()) {
return $intersection;
}

return TypeCombinator::union(...array_map(
static fn (ConstantArrayType $array): ConstantArrayType => $array->inKeyOrderOf(...$shapes),
$intersection->getConstantArrays(),
));
}

/** @see Type::tryIntersect() */
public static function tryIntersectOversizedArray(OversizedArrayType $array, Type $otherType): ?Type
{
Expand Down Expand Up @@ -504,6 +524,11 @@ public static function tryUnionConstantArray(ConstantArrayType $array, Type $oth
return null;
}

// literal arrays with their keys in different orders merge as shapes whose keys come in any order
if ($array->isKeyOrderKnown() && $otherType->isKeyOrderKnown() && !$array->sharesKeyOrderWith($otherType)) {
return self::tryUnionConstantArray($array->forgetKeyOrder(), $otherType->forgetKeyOrder());
}

// $bigger has every key of $smaller, or they cannot merge
[$bigger, $smaller] = count($array->getKeyTypes()) >= count($otherType->getKeyTypes())
? [$array, $otherType]
Expand Down Expand Up @@ -549,15 +574,23 @@ public static function tryUnionConstantArray(ConstantArrayType $array, Type $oth
}

if ($differingKeys === 0) {
return $bigger;
if ($bigger->sharesKeyOrderWith($smaller)) {
return $bigger;
}
// the same keys and values in another order, or in an order one does not know: the keys come in any order
return $bigger->isKeyOrderKnown() ? $smaller->mergeWith($bigger) : $bigger->mergeWith($smaller);
}

if ($differingKeys === 1 && $smallerKeys !== []) {
$merged = $bigger->mergeWith($smaller);
if (
count($biggerValueTypes) === 1
&& $merged->getValueTypes()[0] instanceof UnionType
&& $biggerValueTypes[0]->isSuperTypeOf($smallerValueTypes[0])->no()
// values told apart only by the order of the keys of arrays in them merge; asked both ways, so that
// the union does not depend on which shape is the bigger one
&& self::withoutKeyOrder($biggerValueTypes[0])->isSuperTypeOf(self::withoutKeyOrder($smallerValueTypes[0]))
->and(self::withoutKeyOrder($smallerValueTypes[0])->isSuperTypeOf(self::withoutKeyOrder($biggerValueTypes[0])))
->no()
) {
// `array{'a'}|array{'b'}` stays apart: functions that make keys of the
// values, such as array_fill_keys(), tell the shapes apart by them
Expand All @@ -574,14 +607,17 @@ public static function tryUnionConstantArray(ConstantArrayType $array, Type $oth
if ($hasDifferentValues) {
return null;
}
// a shape that knows its key order holds one in another order, or one that does not know it, after
// forgetting its order: `array{a: mixed, b: mixed}` written in code and `array{a: int, b: int}`
// written in PHPDoc are one unordered shape
if (!$biggerRequiresOtherKey) {
$merged = self::holdShape($bigger, $smaller);
$merged = self::holdShape($bigger->sharesKeyOrderWith($smaller) || !$bigger->isKeyOrderKnown() ? $bigger : $bigger->forgetKeyOrder(), $smaller);
if ($merged !== null) {
return $merged;
}
}
if ($matchedKeys === count($bigger->getKeyTypes())) {
return self::holdShape($smaller, $bigger);
return self::holdShape($smaller->sharesKeyOrderWith($bigger) || !$smaller->isKeyOrderKnown() ? $smaller : $smaller->forgetKeyOrder(), $bigger);
}

return null;
Expand Down Expand Up @@ -625,6 +661,22 @@ private static function holdsValue(Type $holder, Type $held): bool
return false;
}

/** The type with the arrays in it, at any depth, not knowing their key order. */
private static function withoutKeyOrder(Type $type): Type
{
return TypeTraverser::map($type, static function (Type $type, callable $traverse): Type {
// rebuilding a recursive type unions its body, which merges shapes through here again
if ($type instanceof RecursiveType || $type instanceof RecursiveTypeReference) {
return $type;
}
if ($type instanceof ConstantArrayType && !$type instanceof TemplateType && $type->isKeyOrderKnown()) {
return $traverse($type->forgetKeyOrder());
}

return $traverse($type);
});
}

private static function withoutWitnessTypes(Type $type): Type
{
return TypeTraverser::map($type, static function (Type $type, callable $traverse): Type {
Expand Down
3 changes: 3 additions & 0 deletions src/Type/ArrayType.php
Original file line number Diff line number Diff line change
Expand Up @@ -824,6 +824,9 @@ public function intersectKeyArray(Type $otherArraysType): Type
private function intersectConstantArrayShape(ConstantArrayType $constantArray): Type
{
$builder = ConstantArrayTypeBuilder::createEmpty();
if ($constantArray->isKeyOrderKnown()) {
$builder->makeKeyOrderKnown();
}

$valueType = $this->getIterableValueType();
$keyType = $this->getIterableKeyType();
Expand Down
2 changes: 1 addition & 1 deletion src/Type/Combinator/ArrayWidening.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public static function widenValueTypes(ConstantArrayType $array): ConstantArrayT
return $array;
}

return new ConstantArrayType($array->getKeyTypes(), $valueTypes, $array->getNextAutoIndexes(), $array->getOptionalKeys(), $array->isList(), $array->getUnsealedTypes());
return new ConstantArrayType($array->getKeyTypes(), $valueTypes, $array->getNextAutoIndexes(), $array->getOptionalKeys(), $array->isList(), $array->getUnsealedTypes(), $array->isKeyOrderKnown());
}

/** The type as a bare shape, or null when it is not one. */
Expand Down
4 changes: 2 additions & 2 deletions src/Type/Combinator/SameKeysShapeWidening.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ private static function merge(array $arrays): ConstantArrayType
foreach (array_keys($constantScalarValueTypes) as $i) {
$valueTypes[$i] = $placeholder;
}
$array = new ConstantArrayType($array->getKeyTypes(), $valueTypes, $array->getNextAutoIndexes(), $array->getOptionalKeys(), $array->isList(), $array->getUnsealedTypes());
$array = new ConstantArrayType($array->getKeyTypes(), $valueTypes, $array->getNextAutoIndexes(), $array->getOptionalKeys(), $array->isList(), $array->getUnsealedTypes(), $array->isKeyOrderKnown());
}
$merged = $merged === null ? $array : $merged->mergeWith($array);
}
Expand All @@ -118,7 +118,7 @@ private static function merge(array $arrays): ConstantArrayType
$valueTypes[$i] = TypeCombinator::union(...$types);
}

return new ConstantArrayType($merged->getKeyTypes(), $valueTypes, $merged->getNextAutoIndexes(), $merged->getOptionalKeys(), $merged->isList(), $merged->getUnsealedTypes());
return new ConstantArrayType($merged->getKeyTypes(), $valueTypes, $merged->getNextAutoIndexes(), $merged->getOptionalKeys(), $merged->isList(), $merged->getUnsealedTypes(), $merged->isKeyOrderKnown());
}

}
3 changes: 3 additions & 0 deletions src/Type/Combinator/ShapeRemoveRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ public function tryRemove(Type $fromType, Type $typeToRemove): ?Type
|| get_class($typeToRemove) !== ConstantArrayType::class
|| $fromType->isUnsealed()->yes()
|| $typeToRemove->isUnsealed()->yes()
// a shape whose key order is known leaves the other orders of the keys in one that does not know it
|| ($typeToRemove->isKeyOrderKnown() && !$fromType->isKeyOrderKnown())
) {
return null;
}
Expand Down Expand Up @@ -70,6 +72,7 @@ public function tryRemove(Type $fromType, Type $typeToRemove): ?Type
$fromType->getOptionalKeys(),
$fromType->isList(),
$fromType->getUnsealedTypes(),
$fromType->isKeyOrderKnown(),
);
}

Expand Down
Loading
Loading