diff --git a/src/Analyser/ExprHandler/Helper/CountNarrowingHelper.php b/src/Analyser/ExprHandler/Helper/CountNarrowingHelper.php index 50c68fc5712..38ca41ce052 100644 --- a/src/Analyser/ExprHandler/Helper/CountNarrowingHelper.php +++ b/src/Analyser/ExprHandler/Helper/CountNarrowingHelper.php @@ -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()) { @@ -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; + } + } diff --git a/src/Analyser/ExprHandler/Helper/FuncCallScopeEffectsHelper.php b/src/Analyser/ExprHandler/Helper/FuncCallScopeEffectsHelper.php index a7a93a200ec..46ed6276932 100644 --- a/src/Analyser/ExprHandler/Helper/FuncCallScopeEffectsHelper.php +++ b/src/Analyser/ExprHandler/Helper/FuncCallScopeEffectsHelper.php @@ -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, @@ -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]; diff --git a/src/Analyser/MutatingScope.php b/src/Analyser/MutatingScope.php index c64394641f4..4c054c29472 100644 --- a/src/Analyser/MutatingScope.php +++ b/src/Analyser/MutatingScope.php @@ -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(); diff --git a/src/PhpDoc/ConstExprNodeResolver.php b/src/PhpDoc/ConstExprNodeResolver.php index 7d1b0ad824f..3f198d2803f 100644 --- a/src/PhpDoc/ConstExprNodeResolver.php +++ b/src/PhpDoc/ConstExprNodeResolver.php @@ -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; diff --git a/src/Reflection/InitializerExprTypeResolver.php b/src/Reflection/InitializerExprTypeResolver.php index ee7767ab88d..e082709dc63 100644 --- a/src/Reflection/InitializerExprTypeResolver.php +++ b/src/Reflection/InitializerExprTypeResolver.php @@ -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) { @@ -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()) { @@ -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) { diff --git a/src/Reflection/Php/PhpClassReflectionExtension.php b/src/Reflection/Php/PhpClassReflectionExtension.php index e581979d4a6..aadad915686 100644 --- a/src/Reflection/Php/PhpClassReflectionExtension.php +++ b/src/Reflection/Php/PhpClassReflectionExtension.php @@ -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)); } diff --git a/src/Type/ArrayAlgebra.php b/src/Type/ArrayAlgebra.php index 05efec6ba1c..c814a1f15f8 100644 --- a/src/Type/ArrayAlgebra.php +++ b/src/Type/ArrayAlgebra.php @@ -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; @@ -105,6 +106,7 @@ public static function splitConstantArrayAtFiniteValue(ConstantArrayType $array) $array->getOptionalKeys(), $array->isList(), $array->getUnsealedTypes(), + $array->isKeyOrderKnown(), ); } @@ -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 @@ -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()); } @@ -365,6 +368,7 @@ private static function intersectDefiniteConstantArrays(ConstantArrayType $a, Co } $newArray = ConstantArrayTypeBuilder::createEmpty(); + $newArray->makeKeyOrderKnown(); if ($bothUnsealed) { [$unsealedKey, $unsealedValue] = ArrayKeyTemplateHelper::intersectEntryTypes($aUnsealed, $bUnsealed); @@ -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()) { @@ -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 { @@ -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] @@ -549,7 +574,11 @@ 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 !== []) { @@ -557,7 +586,11 @@ public static function tryUnionConstantArray(ConstantArrayType $array, Type $oth 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 @@ -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; @@ -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 { diff --git a/src/Type/ArrayType.php b/src/Type/ArrayType.php index 10433588f52..4e10e0f4ccf 100644 --- a/src/Type/ArrayType.php +++ b/src/Type/ArrayType.php @@ -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(); diff --git a/src/Type/Combinator/ArrayWidening.php b/src/Type/Combinator/ArrayWidening.php index c41ee363804..ef866d99d14 100644 --- a/src/Type/Combinator/ArrayWidening.php +++ b/src/Type/Combinator/ArrayWidening.php @@ -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. */ diff --git a/src/Type/Combinator/SameKeysShapeWidening.php b/src/Type/Combinator/SameKeysShapeWidening.php index 95b2298e50a..ae038aec7f3 100644 --- a/src/Type/Combinator/SameKeysShapeWidening.php +++ b/src/Type/Combinator/SameKeysShapeWidening.php @@ -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); } @@ -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()); } } diff --git a/src/Type/Combinator/ShapeRemoveRule.php b/src/Type/Combinator/ShapeRemoveRule.php index 291f5d21a0c..d925ffa054f 100644 --- a/src/Type/Combinator/ShapeRemoveRule.php +++ b/src/Type/Combinator/ShapeRemoveRule.php @@ -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; } @@ -70,6 +72,7 @@ public function tryRemove(Type $fromType, Type $typeToRemove): ?Type $fromType->getOptionalKeys(), $fromType->isList(), $fromType->getUnsealedTypes(), + $fromType->isKeyOrderKnown(), ); } diff --git a/src/Type/Combinator/SharedKeyShapeWidening.php b/src/Type/Combinator/SharedKeyShapeWidening.php index a9bf647f27d..6dc6391b340 100644 --- a/src/Type/Combinator/SharedKeyShapeWidening.php +++ b/src/Type/Combinator/SharedKeyShapeWidening.php @@ -93,7 +93,8 @@ private static function fold(ConstantArrayType $merged, ConstantArrayType $shape if ($extended === null) { return null; } - $merged = $extended; + // the keys only $shape has go where $shape lists them + $merged = $extended->inMergedKeyOrderOf($merged, $shape); } } diff --git a/src/Type/Constant/ConstantArrayType.php b/src/Type/Constant/ConstantArrayType.php index 8c06607815a..adf62f75aa7 100644 --- a/src/Type/Constant/ConstantArrayType.php +++ b/src/Type/Constant/ConstantArrayType.php @@ -82,6 +82,7 @@ use function array_merge; use function array_pop; use function array_push; +use function array_shift; use function array_slice; use function array_unique; use function array_values; @@ -91,6 +92,7 @@ use function in_array; use function is_int; use function is_string; +use function ksort; use function max; use function min; use function pow; @@ -167,6 +169,7 @@ class ConstantArrayType implements Type * @param list $nextAutoIndexes * @param int[] $optionalKeys * @param array{Type, Type}|null $unsealed + * @param bool $keyOrderKnown false for a shape that only lists the keys that are present, like one written in PHPDoc */ public function __construct( private array $keyTypes, @@ -175,6 +178,7 @@ public function __construct( private array $optionalKeys = [], ?TrinaryLogic $isList = null, ?array $unsealed = null, + private bool $keyOrderKnown = true, ) { assert(count($keyTypes) === count($valueTypes)); @@ -203,6 +207,10 @@ public function __construct( } } $this->isList = $isList; + // a list has its keys in the order it lists them + if ($isList->yes()) { + $this->keyOrderKnown = true; + } if ($unsealed !== null) { // Only a BenevolentUnionType describes with the surrounding parentheses of @@ -238,6 +246,70 @@ public function __construct( /** @var array */ private array $generalizedTypes = []; + /** + * Whether the keys come in the order they are listed. A literal array knows its key order; + * an array shape written in PHPDoc only lists the keys that are present. A list and a shape + * with fewer than two keys know the order either way. + */ + public function isKeyOrderKnown(): bool + { + return $this->keyOrderKnown || count($this->keyTypes) < 2 || $this->isList->yes(); + } + + /** Whether the shape tells apart the orders of two of its keys, beyond what a list does. */ + private function hasKeyOrderToKeep(): bool + { + return $this->keyOrderKnown && count($this->keyTypes) > 1 && !$this->isList->yes(); + } + + /** + * The same shape without the order of its keys, as a PHPDoc shape that lists them. + * A template type's bound keeps it - pass its bound instead. + */ + public function forgetKeyOrder(): self + { + if (!$this->keyOrderKnown) { + return $this; + } + + return new self($this->keyTypes, $this->valueTypes, $this->nextAutoIndexes, $this->optionalKeys, $this->isList, $this->unsealedDeclaration ?? $this->unsealed, false); + } + + private function knowKeyOrder(): self + { + if ($this->keyOrderKnown) { + return $this; + } + + return new self($this->keyTypes, $this->valueTypes, $this->nextAutoIndexes, $this->optionalKeys, $this->isList, $this->unsealedDeclaration ?? $this->unsealed, true); + } + + /** + * Whether both shapes know their key order and list the keys they share in the same order. + * Two such shapes that list them in different orders never hold the same array. + */ + public function sharesKeyOrderWith(self $other): bool + { + if (!$this->isKeyOrderKnown() || !$other->isKeyOrderKnown()) { + return false; + } + + $otherKeyIndexMap = $other->getKeyIndexMap(); + $lastIndex = -1; + foreach ($this->keyTypes as $keyType) { + $otherIndex = $otherKeyIndexMap[$keyType->getValue()] ?? null; + if ($otherIndex === null) { + continue; + } + if ($otherIndex < $lastIndex) { + return false; + } + $lastIndex = $otherIndex; + } + + return true; + } + public function isSealed(): TrinaryLogic { return $this->isUnsealed()->negate(); @@ -331,7 +403,7 @@ protected function recreate( ?array $unsealed, ): self { - return new self($keyTypes, $valueTypes, $nextAutoIndexes, $optionalKeys, $isList, $this->keepUnsealedDeclaration($unsealed)); + return new self($keyTypes, $valueTypes, $nextAutoIndexes, $optionalKeys, $isList, $this->keepUnsealedDeclaration($unsealed), $this->keyOrderKnown); } /** @@ -518,6 +590,9 @@ public function getAllArrays(): array } $builder = ConstantArrayTypeBuilder::createEmpty(); + if ($this->keyOrderKnown) { + $builder->makeKeyOrderKnown(); + } $builder->disableArrayDegradation(); foreach ($keys as $i) { $builder->setOffsetValueType($this->keyTypes[$i], $this->valueTypes[$i]); @@ -591,6 +666,49 @@ public function sortKeys(): self $indices = array_keys($this->keyTypes); usort($indices, fn (int $a, int $b): int => $this->keyTypes[$a]->getValue() <=> $this->keyTypes[$b]->getValue()); + return $this->reorderKeys($indices); + } + + /** + * This shape with its keys in the order of the first of the shapes that knows its key order + * and lists every key of this one, or without a known key order when none of them does. + * Fits the intersection of the shapes, whose keys come from more than one of them. + */ + public function inKeyOrderOf(self ...$shapes): self + { + if (!$this->hasKeyOrderToKeep()) { + return $this; + } + + foreach ($shapes as $shape) { + if (!$shape->isKeyOrderKnown()) { + continue; + } + + $shapeKeyIndexMap = $shape->getKeyIndexMap(); + $indices = []; + foreach ($this->keyTypes as $i => $keyType) { + $shapeIndex = $shapeKeyIndexMap[$keyType->getValue()] ?? null; + if ($shapeIndex === null) { + continue 2; + } + $indices[$shapeIndex] = $i; + } + ksort($indices); + + return $this->reorderKeys(array_values($indices)); + } + + return $this->forgetKeyOrder(); + } + + /** @param list $indices the indices of the keys in their new order */ + private function reorderKeys(array $indices): self + { + if ($indices === array_keys($this->keyTypes)) { + return $this; + } + $newKeyTypes = []; $newValueTypes = []; $indexMap = []; @@ -622,6 +740,18 @@ public function accepts(Type $type, bool $strictTypes): AcceptsResult return $type->isAcceptedBy($this, $strictTypes); } + $constantArrays = $type->getConstantArrays(); + if (count($constantArrays) === 1) { + // the shape that does not know its key order may hold its keys in another order than this one + if ($this->hasKeyOrderToKeep() && !$constantArrays[0]->isKeyOrderKnown()) { + return $this->forgetKeyOrder()->accepts($type, $strictTypes)->and(AcceptsResult::createMaybe()); + } + // an array never has its keys in two orders + if ($this->isKeyOrderKnown() && $constantArrays[0]->isKeyOrderKnown() && !$this->sharesKeyOrderWith($constantArrays[0])) { + return AcceptsResult::createNo(); + } + } + $isUnsealed = $this->isUnsealed(); if (!$isUnsealed->yes()) { if ($type instanceof self && count($this->keyTypes) === 0) { @@ -882,6 +1012,11 @@ public function isSuperTypeOf(Type $type): IsSuperTypeOfResult } if ($type instanceof self) { + // an array never has its keys in two orders + if ($this->isKeyOrderKnown() && $type->isKeyOrderKnown() && !$this->sharesKeyOrderWith($type)) { + return IsSuperTypeOfResult::createNo(); + } + $thisUnsealedness = $this->isUnsealed(); $typeUnsealedness = $type->isUnsealed(); $bothDefinite = $this->unsealed !== null && $type->unsealed !== null; @@ -1021,6 +1156,11 @@ public function isSuperTypeOf(Type $type): IsSuperTypeOfResult } } + // the shape that does not know its key order may hold its keys in another order than this one + if ($this->hasKeyOrderToKeep() && !$type->isKeyOrderKnown()) { + $results[] = IsSuperTypeOfResult::createMaybe(); + } + return IsSuperTypeOfResult::createYes()->and(...$results); } @@ -1100,18 +1240,40 @@ public function equals(Type $type): bool return false; } - foreach ($this->keyTypes as $i => $keyType) { - $valueType = $this->valueTypes[$i]; - if (!$valueType->equals($type->valueTypes[$i])) { - return false; + $isKeyOrderKnown = $this->isKeyOrderKnown(); + if ($isKeyOrderKnown !== $type->isKeyOrderKnown()) { + return false; + } + + if ($isKeyOrderKnown) { + foreach ($this->keyTypes as $i => $keyType) { + $valueType = $this->valueTypes[$i]; + if (!$valueType->equals($type->valueTypes[$i])) { + return false; + } + if (!$keyType->equals($type->keyTypes[$i])) { + return false; + } } - if (!$keyType->equals($type->keyTypes[$i])) { + + if ($this->optionalKeys !== $type->optionalKeys) { return false; } - } - - if ($this->optionalKeys !== $type->optionalKeys) { - return false; + } else { + // shapes that do not know their key order are the same type whatever order they list their keys in + $otherKeyIndexMap = $type->getKeyIndexMap(); + foreach ($this->keyTypes as $i => $keyType) { + $j = $otherKeyIndexMap[$keyType->getValue()] ?? null; + if ($j === null) { + return false; + } + if (!$this->valueTypes[$i]->equals($type->valueTypes[$j])) { + return false; + } + if ($this->isOptionalKey($i) !== $type->isOptionalKey($j)) { + return false; + } + } } // Both `unsealed === null` (legacy / pre-bleeding-edge, where @@ -1812,6 +1974,11 @@ public function chunkArray(Type $lengthType, TrinaryLogic $preserveKeys): Type return $this->traitChunkArray($lengthType, $preserveKeys); } + if (!$this->isKeyOrderKnown() && !$preserveKeys->yes()) { + // which of the values come in which chunk is not known + return $this->getValuesArray()->chunkArray($lengthType, $preserveKeys); + } + $biggerOne = IntegerRangeType::fromInterval(1, null); $finiteTypes = $lengthType->getFiniteTypes(); if ($biggerOne->isSuperTypeOf($lengthType)->yes() && count($finiteTypes) < self::CHUNK_FINITE_TYPES_LIMIT) { @@ -1824,6 +1991,9 @@ public function chunkArray(Type $lengthType, TrinaryLogic $preserveKeys): Type $length = $finiteType->getValue(); $builder = ConstantArrayTypeBuilder::createEmpty(); + if ($this->keyOrderKnown) { + $builder->makeKeyOrderKnown(); + } $keyTypesCount = count($this->keyTypes); for ($i = 0; $i < $keyTypesCount; $i += $length) { @@ -1843,6 +2013,9 @@ public function chunkArray(Type $lengthType, TrinaryLogic $preserveKeys): Type public function fillKeysArray(Type $valueType): Type { $builder = ConstantArrayTypeBuilder::createEmpty(); + if ($this->keyOrderKnown) { + $builder->makeKeyOrderKnown(); + } foreach ($this->valueTypes as $i => $keyType) { if ($keyType->isInteger()->no()) { @@ -1876,6 +2049,9 @@ public function fillKeysArray(Type $valueType): Type public function flipArray(): Type { $builder = ConstantArrayTypeBuilder::createEmpty(); + if ($this->keyOrderKnown) { + $builder->makeKeyOrderKnown(); + } foreach ($this->keyTypes as $i => $keyType) { $valueType = $this->valueTypes[$i]; @@ -1910,6 +2086,9 @@ public function flipArray(): Type public function intersectKeyArray(Type $otherArraysType): Type { $builder = ConstantArrayTypeBuilder::createEmpty(); + if ($this->keyOrderKnown) { + $builder->makeKeyOrderKnown(); + } foreach ($this->keyTypes as $i => $keyType) { $valueType = $this->valueTypes[$i]; @@ -1937,12 +2116,25 @@ public function intersectKeyArray(Type $otherArraysType): Type public function popArray(): Type { + if (!$this->isKeyOrderKnown()) { + // the last element can be any of them + return $this->makeAllArrayKeysOptional(); + } + return $this->removeLastElements(1); } public function reverseArray(TrinaryLogic $preserveKeys): Type { + if (!$this->isKeyOrderKnown() && !$preserveKeys->yes() && $this->listsIntegerKey()) { + // the integer keys are renumbered by positions that are not known + return $this->withoutPositionsOfKeys()->reverseArray($preserveKeys); + } + $builder = ConstantArrayTypeBuilder::createEmpty(); + if ($this->keyOrderKnown) { + $builder->makeKeyOrderKnown(); + } for ($i = count($this->keyTypes) - 1; $i >= 0; $i--) { $offsetType = $preserveKeys->yes() || $this->keyTypes[$i]->isInteger()->no() @@ -1991,6 +2183,11 @@ public function searchArray(Type $needleType, ?TrinaryLogic $strict = null): Typ } $matches[] = $this->keyTypes[$index]; + + // the search stops at the first key that surely matches, unless the keys can come in any order + if ($hasIdenticalValue && $this->isKeyOrderKnown()) { + break; + } } // Unsealed extras can host additional entries beyond the explicit @@ -2023,6 +2220,13 @@ public function searchArray(Type $needleType, ?TrinaryLogic $strict = null): Typ public function shiftArray(): Type { + if (!$this->isKeyOrderKnown()) { + // the first element can be any of them, and the integer keys are renumbered by positions that are not known + return $this->listsIntegerKey() + ? $this->withoutPositionsOfKeys()->shiftArray() + : $this->makeAllArrayKeysOptional(); + } + return $this->removeFirstElements(1); } @@ -2038,6 +2242,13 @@ public function sliceArray(Type $offsetType, Type $lengthType, TrinaryLogic $pre return $this; } + if (!$this->isKeyOrderKnown()) { + // which of the keys come at the positions is not known, and the integer keys are renumbered by them + return $preserveKeys->yes() || !$this->listsIntegerKey() + ? $this->makeAllArrayKeysOptional() + : $this->withoutPositionsOfKeys()->sliceArray($offsetType, $lengthType, $preserveKeys); + } + $offset = $offsetType instanceof ConstantIntegerType ? $offsetType->getValue() : null; if ($lengthType instanceof ConstantIntegerType) { @@ -2102,6 +2313,9 @@ public function sliceArray(Type $offsetType, Type $lengthType, TrinaryLogic $pre } $builder = ConstantArrayTypeBuilder::createEmpty(); + if ($this->keyOrderKnown) { + $builder->makeKeyOrderKnown(); + } $nonOptionalElementsCount = 0; $hasOptional = false; @@ -2151,6 +2365,11 @@ public function spliceArray(Type $offsetType, Type $lengthType, Type $replacemen return $this; } + if (!$this->isKeyOrderKnown()) { + // which of the keys come at the positions is not known + return $this->degradeToGeneralArray()->spliceArray($offsetType, $lengthType, $replacementType); + } + $offset = $offsetType instanceof ConstantIntegerType ? $offsetType->getValue() : null; if ($lengthType instanceof ConstantIntegerType) { @@ -2196,6 +2415,9 @@ public function spliceArray(Type $offsetType, Type $lengthType, Type $replacemen $optionalKeysBeforeReplacement = 0; $builder = ConstantArrayTypeBuilder::createEmpty(); + if ($this->keyOrderKnown) { + $builder->makeKeyOrderKnown(); + } for ($i = 0;; $i++) { $isOptional = $this->isOptionalKey($i); @@ -2328,6 +2550,9 @@ public function truncateListToSize(Type $sizeType): Type } $builder = ConstantArrayTypeBuilder::createEmpty(); + if ($this->keyOrderKnown) { + $builder->makeKeyOrderKnown(); + } foreach ($builderData as [$offsetType, $valueType, $optional]) { $builder->setOffsetValueType($offsetType, $valueType, $optional); } @@ -2406,6 +2631,10 @@ public function getArraySize(): Type public function getFirstIterableKeyType(): Type { + if (!$this->isKeyOrderKnown()) { + return $this->getIterableKeyType(); + } + $keyTypes = []; foreach ($this->keyTypes as $i => $keyType) { $keyTypes[] = $keyType; @@ -2429,6 +2658,10 @@ public function getFirstIterableKeyType(): Type public function getLastIterableKeyType(): Type { + if (!$this->isKeyOrderKnown()) { + return $this->getIterableKeyType(); + } + $keyTypes = []; for ($i = count($this->keyTypes) - 1; $i >= 0; $i--) { $keyTypes[] = $this->keyTypes[$i]; @@ -2452,6 +2685,10 @@ public function getLastIterableKeyType(): Type public function getFirstIterableValueType(): Type { + if (!$this->isKeyOrderKnown()) { + return $this->getIterableValueType(); + } + $valueTypes = []; foreach ($this->valueTypes as $i => $valueType) { $valueTypes[] = $valueType; @@ -2469,6 +2706,10 @@ public function getFirstIterableValueType(): Type public function getLastIterableValueType(): Type { + if (!$this->isKeyOrderKnown()) { + return $this->getIterableValueType(); + } + $valueTypes = []; for ($i = count($this->keyTypes) - 1; $i >= 0; $i--) { $valueTypes[] = $this->valueTypes[$i]; @@ -2580,6 +2821,9 @@ private function removeLastElements(int $length): self private function removeFirstElements(int $length, bool $reindex = true): Type { $builder = ConstantArrayTypeBuilder::createEmpty(); + if ($this->keyOrderKnown) { + $builder->makeKeyOrderKnown(); + } $optionalKeysIgnored = 0; foreach ($this->keyTypes as $i => $keyType) { @@ -2738,6 +2982,98 @@ public function getValuesArray(): self return $this->getKeysOrValuesArray($this->valueTypes, $this->unsealed[1] ?? null); } + /** + * The values in the order the array has them, for code that walks the values by position: this shape when it + * knows its key order, otherwise the list of the values that can come at each position. + */ + public function getValuesInKeyOrder(): self + { + return $this->isKeyOrderKnown() ? $this : $this->getValuesArray(); + } + + /** + * This shape as code that renumbers its integer keys by their positions, like array_merge() and unpacking, sees + * it: when it does not know its key order, each of the integer keys holds any of their values, the required + * ones listed first. The string keys keep their values. + */ + public function inRenumberingOrder(): self + { + if ($this->isKeyOrderKnown()) { + return $this; + } + + $integerValueTypes = []; + $requiredIntegerKeys = []; + $optionalIntegerKeys = []; + foreach ($this->keyTypes as $i => $keyType) { + if (!$keyType instanceof ConstantIntegerType) { + continue; + } + + $integerValueTypes[] = $this->valueTypes[$i]; + if ($this->isOptionalKey($i)) { + $optionalIntegerKeys[] = $keyType; + } else { + $requiredIntegerKeys[] = $keyType; + } + } + if (count($integerValueTypes) < 2) { + return $this; + } + + $integerValueType = TypeCombinator::union(...$integerValueTypes); + $integerKeys = array_merge($requiredIntegerKeys, $optionalIntegerKeys); + $keyTypes = []; + $valueTypes = []; + $optionalKeys = []; + foreach ($this->keyTypes as $i => $keyType) { + if ($keyType instanceof ConstantIntegerType) { + $keyType = array_shift($integerKeys); + if ($keyType === null) { + throw new ShouldNotHappenException(); + } + $valueTypes[] = $integerValueType; + $isOptional = in_array($keyType, $optionalIntegerKeys, true); + } else { + $valueTypes[] = $this->valueTypes[$i]; + $isOptional = $this->isOptionalKey($i); + } + $keyTypes[] = $keyType; + if (!$isOptional) { + continue; + } + + $optionalKeys[] = count($keyTypes) - 1; + } + + $renumbered = $this->recreate($keyTypes, $valueTypes, $this->nextAutoIndexes, $optionalKeys, $this->isList, $this->unsealed); + + // with only integer keys, each position holds any of the values, so the positions are all the order there is + return count($integerValueTypes) === count($this->keyTypes) ? $renumbered->knowKeyOrder() : $renumbered; + } + + private function listsIntegerKey(): bool + { + foreach ($this->keyTypes as $keyType) { + if ($keyType instanceof ConstantIntegerType) { + return true; + } + } + + return false; + } + + /** + * The values at positions any of them can come at, for operations that renumber integer keys by position: + * the list of the values when every key is an integer, a general array otherwise. + */ + private function withoutPositionsOfKeys(): Type + { + return $this->getIterableKeyType()->isInteger()->yes() + ? $this->getValuesArray() + : $this->degradeToGeneralArray(); + } + /** * @param array $types */ @@ -2758,6 +3094,26 @@ private function getKeysOrValuesArray(array $types, ?Type $unsealedSourceType): $resultUnsealed = [IntegerRangeType::createAllGreaterThanOrEqualTo(0), $unsealedSourceType]; } + if (!$this->isKeyOrderKnown()) { + // any of the keys, and any of the extras, can come at any position + $valueType = TypeCombinator::union(...$types, ...($resultUnsealed !== null ? [$resultUnsealed[1]] : [])); + $requiredCount = $count - count($this->optionalKeys); + $keyTypes = []; + $valueTypes = []; + $optionalKeys = []; + for ($i = 0; $i < $count; $i++) { + $keyTypes[] = new ConstantIntegerType($i); + $valueTypes[] = $valueType; + if ($i < $requiredCount) { + continue; + } + + $optionalKeys[] = $i; + } + + return $this->recreate($keyTypes, $valueTypes, $autoIndexes, $optionalKeys, TrinaryLogic::createYes(), $resultUnsealed); + } + if ($this->isList->yes()) { // Optimized version for lists: Assume that if a later key exists, then earlier keys also exist. $keyTypes = array_map( @@ -2829,7 +3185,8 @@ private function getKeysOrValuesArray(array $types, ?Type $unsealedSourceType): public function describe(VerbosityLevel $level): string { - $arrayName = $this->shouldBeDescribedAsAList() ? 'list' : 'array'; + $arrayName = $this->shouldBeDescribedAsAList(true) ? 'list' : 'array'; + $typeOnlyArrayName = $this->shouldBeDescribedAsAList(false) ? 'list' : 'array'; $describeValue = function (bool $truncate) use ($level, $arrayName): string { $items = []; @@ -2890,14 +3247,16 @@ public function describe(VerbosityLevel $level): string } return sprintf( - '%s{%s%s}', + '%s{%s%s}%s', $arrayName, implode(', ', $exportValuesOnly ? $values : $items), $append, + $level->isCache() && !$this->isKeyOrderKnown() ? '(unordered)' : '', ); }; return $level->handle( - function () use ($arrayName, $level): string { + function () use ($typeOnlyArrayName, $level): string { + $arrayName = $typeOnlyArrayName; if ($this->isIterableAtLeastOnce()->no()) { return $arrayName; } @@ -2915,7 +3274,8 @@ function () use ($arrayName, $level): string { ); } - private function shouldBeDescribedAsAList(): bool + /** @param bool $namingKeys whether the description names the keys, as a shape does */ + private function shouldBeDescribedAsAList(bool $namingKeys = true): bool { if (!$this->isList->yes()) { return false; @@ -2925,7 +3285,8 @@ private function shouldBeDescribedAsAList(): bool return false; } - if (count($this->optionalKeys) > 1) { + // with bleeding edge, a shape that lists two or more keys is not a list + if (count($this->optionalKeys) > 1 || ($namingKeys && count($this->keyTypes) > 1 && BleedingEdgeToggle::isBleedingEdge())) { return true; } @@ -3448,8 +3809,13 @@ public function mergeWith(self $otherArray): self $isList = $mergedIsSealed ? $naiveIsList->or(self::inferIsListFromShape($keyTypes, $optionalKeys)) : $naiveIsList; + $sharesKeyOrder = $this->sharesKeyOrderWith($otherArray); + if (!$sharesKeyOrder) { + // the keys do not come in one known order: a list in one order may not be one in the other + $isList = TrinaryLogic::extremeIdentity($this->isList, $otherArray->isList); + } - return $this->recreate( + $merged = $this->recreate( $keyTypes, $valueTypes, $nextAutoIndexes, @@ -3457,6 +3823,74 @@ public function mergeWith(self $otherArray): self $isList, $resultUnsealed, ); + + // the merged shape knows its key order only when both shapes it merges know the same one + return !$sharesKeyOrder && $merged instanceof TemplateType ? $merged : $merged->inMergedKeyOrderOf($this, $otherArray); + } + + /** + * This shape, holding the keys of two shapes merged into one, with its keys in an order both of them keep: + * a key only one of them lists stays between the keys it is listed between there. Without a known key order + * when the shapes do not list the keys they share in one known order. + */ + public function inMergedKeyOrderOf(self $a, self $b): self + { + $mergedKeyTypes = $a->getKeyTypesInMergedOrderWith($b); + if ($mergedKeyTypes === null) { + return $this->forgetKeyOrder(); + } + + $positions = []; + foreach ($mergedKeyTypes as $position => $keyType) { + $positions[$keyType->getValue()] = $position; + } + + $indices = []; + foreach ($this->keyTypes as $k => $keyType) { + $indices[$positions[$keyType->getValue()]] = $k; + } + ksort($indices); + + return $this->reorderKeys(array_values($indices)); + } + + /** + * The keys of both shapes in an order both of them keep: a key only one of them lists stays between the keys + * it is listed between there. Null when the shapes do not list the keys they share in one known order. + * + * @return list|null + */ + public function getKeyTypesInMergedOrderWith(self $other): ?array + { + if (!$this->sharesKeyOrderWith($other)) { + return null; + } + + $keyIndexMap = $this->getKeyIndexMap(); + $otherKeyIndexMap = $other->getKeyIndexMap(); + $keyTypes = []; + $i = 0; + $j = 0; + $count = count($this->keyTypes); + $otherCount = count($other->keyTypes); + while ($i < $count || $j < $otherCount) { + if ($i < $count && !array_key_exists($this->keyTypes[$i]->getValue(), $otherKeyIndexMap)) { + $keyTypes[] = $this->keyTypes[$i]; + $i++; + continue; + } + if ($j < $otherCount && !array_key_exists($other->keyTypes[$j]->getValue(), $keyIndexMap)) { + $keyTypes[] = $other->keyTypes[$j]; + $j++; + continue; + } + // the next key of both is the same shared key + $keyTypes[] = $this->keyTypes[$i]; + $i++; + $j++; + } + + return $keyTypes; } private function legacyMergeWith(self $otherArray): self @@ -3491,8 +3925,15 @@ private function legacyMergeWith(self $otherArray): self $isList = $mergedIsSealed ? $naiveIsList->or(self::inferIsListFromShape($this->keyTypes, $optionalKeys)) : $naiveIsList; + $sharesKeyOrder = $this->sharesKeyOrderWith($otherArray); + if (!$sharesKeyOrder) { + $isList = TrinaryLogic::extremeIdentity($this->isList, $otherArray->isList); + } + + $merged = $this->recreate($this->keyTypes, $valueTypes, $nextAutoIndexes, $optionalKeys, $isList, $this->unsealed); - return $this->recreate($this->keyTypes, $valueTypes, $nextAutoIndexes, $optionalKeys, $isList, $this->unsealed); + // the merged shape knows its key order only when both shapes it merges know the same one + return !$sharesKeyOrder && $merged instanceof TemplateType ? $merged : $merged->inMergedKeyOrderOf($this, $otherArray); } /** @@ -3655,6 +4096,12 @@ public function makeList(): Type return new NeverType(); } + if (!$this->isKeyOrderKnown()) { + // a list has its keys in ascending order + $sorted = $this->sortKeys(); + return (new self($sorted->keyTypes, $sorted->valueTypes, $sorted->nextAutoIndexes, $sorted->optionalKeys, $sorted->isList, $sorted->unsealedDeclaration ?? $sorted->unsealed, true))->makeList(); + } + // isList is Maybe. In a sealed shape a key past a gap in the 0..n sequence // (or any non-integer key) can never appear in a list, so keep only the // contiguous 0..m prefix. Unsealed extras may fill the gaps, so keep every @@ -3675,6 +4122,9 @@ public function makeList(): Type if (count($keptPositions) < count($this->keyTypes)) { $builder = ConstantArrayTypeBuilder::createEmpty(); + if ($this->keyOrderKnown) { + $builder->makeKeyOrderKnown(); + } foreach ($keptPositions as $position) { $builder->setOffsetValueType( $this->keyTypes[$position], @@ -3756,6 +4206,9 @@ public function makeAllArrayKeysOptional(): Type public function changeKeyCaseArray(?int $case): Type { $builder = ConstantArrayTypeBuilder::createEmpty(); + if ($this->keyOrderKnown) { + $builder->makeKeyOrderKnown(); + } foreach ($this->keyTypes as $i => $keyType) { if ($keyType instanceof ConstantStringType) { $newKeyType = self::foldConstantStringKeyCase($keyType, $case); @@ -3780,6 +4233,9 @@ public function filterArrayRemovingFalsey(): Type { $falseyTypes = StaticTypeFactory::falsey(); $builder = ConstantArrayTypeBuilder::createEmpty(); + if ($this->keyOrderKnown) { + $builder->makeKeyOrderKnown(); + } foreach ($this->keyTypes as $i => $keyType) { $value = $this->valueTypes[$i]; $isFalsey = $falseyTypes->isSuperTypeOf($value); @@ -4000,8 +4456,13 @@ public function getFiniteTypes(): array } } + $emptyPartial = ConstantArrayTypeBuilder::createEmpty(); + if ($this->keyOrderKnown) { + $emptyPartial->makeKeyOrderKnown(); + } + /** @var list $partials */ - $partials = [ConstantArrayTypeBuilder::createEmpty()]; + $partials = [$emptyPartial]; foreach ($this->keyTypes as $i => $keyType) { $finiteValueTypes = $finiteValueTypesPerKey[$i]; diff --git a/src/Type/Constant/ConstantArrayTypeBuilder.php b/src/Type/Constant/ConstantArrayTypeBuilder.php index af350aff63a..789eaeefcda 100644 --- a/src/Type/Constant/ConstantArrayTypeBuilder.php +++ b/src/Type/Constant/ConstantArrayTypeBuilder.php @@ -19,14 +19,17 @@ use PHPStan\Type\TypeCombinator; use PHPStan\Type\TypeUtils; use function array_filter; +use function array_keys; use function array_map; use function array_unique; use function array_values; use function count; use function in_array; use function is_float; +use function is_int; use function max; use function min; +use function usort; /** * @api @@ -48,6 +51,9 @@ final class ConstantArrayTypeBuilder private TrinaryLogic $isNonEmpty; + /** An empty builder does not know in which order its keys come until makeKeyOrderKnown() says so. */ + private bool $keyOrderKnown = false; + /** * @param list $keyTypes * @param array $valueTypes @@ -103,6 +109,7 @@ public static function createFromConstantArray(ConstantArrayType $startArrayType $startArrayType->getUnsealedTypes(), ); $builder->isNonEmpty = $startArrayType->isIterableAtLeastOnce(); + $builder->keyOrderKnown = $startArrayType->isKeyOrderKnown(); // an array built on keeps the unsealed key that declares a template for as long as its extras stay as they are $unsealedEntryTypes = ($startArrayType->isUnsealed()->yes() ? $startArrayType->getUnsealedDeclaredTypes() : null); @@ -117,6 +124,44 @@ public static function createFromConstantArray(ConstantArrayType $startArrayType return $builder; } + /** The keys come in the order they are set, as in a literal array. */ + public function makeKeyOrderKnown(): void + { + $this->keyOrderKnown = true; + } + + /** The array is built without the order of its keys, as a PHPDoc shape that lists them. */ + public function forgetKeyOrder(): void + { + $this->keyOrderKnown = false; + } + + /** + * The keys come in any order, so the array can be a list when they could come in ascending + * order, but does not surely come as one. + */ + public function forgetListKeyOrder(): void + { + // a builder that degrades has keys without a value to sort them by + if ($this->degradeToGeneralArray) { + $this->isList = $this->isList->and(TrinaryLogic::createMaybe()); + return; + } + + /** @var list $keyTypes */ + $keyTypes = $this->keyTypes; + $indices = array_keys($keyTypes); + usort($indices, static fn (int $a, int $b): int => [!is_int($keyTypes[$a]->getValue()), $keyTypes[$a]->getValue()] <=> [!is_int($keyTypes[$b]->getValue()), $keyTypes[$b]->getValue()]); + + $sorted = self::createEmpty(); + foreach ($indices as $i) { + $sorted->setOffsetValueType($keyTypes[$i], $this->valueTypes[$i], in_array($i, $this->optionalKeys, true)); + } + + // a single key has no order to forget + $this->isList = count($this->keyTypes) < 2 ? $sorted->isList : $sorted->isList->and(TrinaryLogic::createMaybe()); + } + public function makeUnsealed(Type $keyType, Type $valueType): void { $this->setUnsealed([$keyType, $valueType]); @@ -510,6 +555,7 @@ public function disableArrayDegradation(): void public function getArray(): Type { $keyTypesCount = count($this->keyTypes); + $isList = $this->getListness(); if ($keyTypesCount === 0) { if ($this->unsealed !== null) { $isExplicitNever = $this->unsealed[0] instanceof NeverType && $this->unsealed[0]->isExplicit(); @@ -528,7 +574,7 @@ public function getArray(): Type if (!$this->degradeToGeneralArray) { /** @var list $keyTypes */ $keyTypes = $this->keyTypes; - $array = new ConstantArrayType($keyTypes, $this->valueTypes, $this->nextAutoIndexes, $this->optionalKeys, $this->isList, $this->getUnsealedForArray()); + $array = new ConstantArrayType($keyTypes, $this->valueTypes, $this->nextAutoIndexes, $this->optionalKeys, $isList, $this->getUnsealedForArray(), $this->keyOrderKnown); if ($this->isNonEmpty->yes() && !$array->isIterableAtLeastOnce()->yes()) { return TypeCombinator::intersect($array, new NonEmptyArrayType()); } @@ -575,7 +621,7 @@ public function getArray(): Type $types[] = new OversizedArrayType(); } - if ($this->isList->yes()) { + if ($isList->yes()) { $types[] = new AccessoryArrayListType(); } @@ -588,7 +634,17 @@ public function getArray(): Type public function isList(): bool { - return $this->isList->yes(); + return $this->getListness()->yes(); + } + + private function getListness(): TrinaryLogic + { + // keys set in no known order do not say they come as a list, only that they can + if (!$this->keyOrderKnown && count($this->keyTypes) > 1 && BleedingEdgeToggle::isBleedingEdge()) { + return $this->isList->and(TrinaryLogic::createMaybe()); + } + + return $this->isList; } } diff --git a/src/Type/ConstantTypeHelper.php b/src/Type/ConstantTypeHelper.php index 04cb39180c0..d2703a31902 100644 --- a/src/Type/ConstantTypeHelper.php +++ b/src/Type/ConstantTypeHelper.php @@ -51,6 +51,7 @@ public static function getTypeFromValue($value): Type return self::getOversizedArrayType($value); } $arrayBuilder = ConstantArrayTypeBuilder::createEmpty(); + $arrayBuilder->makeKeyOrderKnown(); foreach ($value as $k => $v) { $arrayBuilder->setOffsetValueType(self::getTypeFromValue($k), self::getTypeFromValue($v)); } diff --git a/src/Type/Generic/TemplateConstantArrayType.php b/src/Type/Generic/TemplateConstantArrayType.php index 5e506cb6b01..7d635d2fe0c 100644 --- a/src/Type/Generic/TemplateConstantArrayType.php +++ b/src/Type/Generic/TemplateConstantArrayType.php @@ -29,7 +29,7 @@ public function __construct( ?Type $default, ) { - parent::__construct($bound->getKeyTypes(), $bound->getValueTypes(), $bound->getNextAutoIndexes(), $bound->getOptionalKeys(), $bound->isList()); + parent::__construct($bound->getKeyTypes(), $bound->getValueTypes(), $bound->getNextAutoIndexes(), $bound->getOptionalKeys(), $bound->isList(), keyOrderKnown: $bound->isKeyOrderKnown()); $this->scope = $scope; $this->strategy = $templateTypeStrategy; $this->variance = $templateTypeVariance; @@ -52,7 +52,7 @@ protected function recreate( $this->strategy, $this->variance, $this->name, - new ConstantArrayType($keyTypes, $valueTypes, $nextAutoIndexes, $optionalKeys, $isList, $this->keepUnsealedDeclaration($unsealed)), + new ConstantArrayType($keyTypes, $valueTypes, $nextAutoIndexes, $optionalKeys, $isList, $this->keepUnsealedDeclaration($unsealed), $this->isKeyOrderKnown()), $this->default, ); } diff --git a/src/Type/Generic/TemplateTypeHelper.php b/src/Type/Generic/TemplateTypeHelper.php index 022a3a68d63..5043c19c352 100644 --- a/src/Type/Generic/TemplateTypeHelper.php +++ b/src/Type/Generic/TemplateTypeHelper.php @@ -4,6 +4,7 @@ use PHPStan\Reflection\ParametersAcceptor; use PHPStan\Turbo\ShadowedByTurboExtension; +use PHPStan\Type\Constant\ConstantArrayType; use PHPStan\Type\ErrorType; use PHPStan\Type\GeneralizePrecision; use PHPStan\Type\NarrowedSubjectType; @@ -242,6 +243,15 @@ public static function generalizeInferredTemplateType(TemplateType $templateType } elseif ($type->isConstantValue()->yes() && (!$templateType->getBound()->isScalar()->yes() || $isArrayKey)) { $type = $type->generalize(GeneralizePrecision::templateArgument()); } + + // the order of the keys of an array written in code is as specific as its values + $type = TypeTraverser::map($type, static function (Type $type, callable $traverse): Type { + if ($type instanceof ConstantArrayType && !$type instanceof TemplateType) { + $type = $type->forgetKeyOrder(); + } + + return $traverse($type); + }); } return $type; diff --git a/src/Type/IntersectionType.php b/src/Type/IntersectionType.php index 79d0dfea979..e6b7f273800 100644 --- a/src/Type/IntersectionType.php +++ b/src/Type/IntersectionType.php @@ -927,12 +927,12 @@ public function getIterableKeyType(): Type public function getFirstIterableKeyType(): Type { - return $this->intersectTypes(static fn (Type $type): Type => $type->getIterableKeyType()); + return $this->intersectTypes(static fn (Type $type): Type => $type->getFirstIterableKeyType()); } public function getLastIterableKeyType(): Type { - return $this->intersectTypes(static fn (Type $type): Type => $type->getIterableKeyType()); + return $this->intersectTypes(static fn (Type $type): Type => $type->getLastIterableKeyType()); } public function getIterableValueType(): Type @@ -952,12 +952,12 @@ public function getIterableValueType(): Type public function getFirstIterableValueType(): Type { - return $this->intersectTypes(static fn (Type $type): Type => $type->getIterableValueType()); + return $this->intersectTypes(static fn (Type $type): Type => $type->getFirstIterableValueType()); } public function getLastIterableValueType(): Type { - return $this->intersectTypes(static fn (Type $type): Type => $type->getIterableValueType()); + return $this->intersectTypes(static fn (Type $type): Type => $type->getLastIterableValueType()); } public function isArray(): TrinaryLogic diff --git a/src/Type/LateResolvableArrayShapeType.php b/src/Type/LateResolvableArrayShapeType.php index 177ebda9233..c821b6bf6b2 100644 --- a/src/Type/LateResolvableArrayShapeType.php +++ b/src/Type/LateResolvableArrayShapeType.php @@ -2,6 +2,7 @@ namespace PHPStan\Type; +use PHPStan\DependencyInjection\BleedingEdgeToggle; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode; use PHPStan\PhpDocParser\Ast\ConstExpr\ConstFetchNode; @@ -219,6 +220,13 @@ protected function getResult(): Type $builder->setOffsetValueType($keyType, $valueType, $optional); } + // a shape that names its keys only says they are present, not in which order + if ($explicitKeyValues === []) { + $builder->makeKeyOrderKnown(); + } elseif (BleedingEdgeToggle::isBleedingEdge()) { + $builder->forgetListKeyOrder(); + } + $isList = in_array($this->kind, [ ArrayShapeNode::KIND_LIST, ArrayShapeNode::KIND_NON_EMPTY_LIST, diff --git a/src/Type/Php/ArrayColumnHelper.php b/src/Type/Php/ArrayColumnHelper.php index c2121f50f4d..1fda60b8ae8 100644 --- a/src/Type/Php/ArrayColumnHelper.php +++ b/src/Type/Php/ArrayColumnHelper.php @@ -82,6 +82,13 @@ public function handleAnyArray(Type $arrayType, Type $columnType, Type $indexTyp public function handleConstantArray(ConstantArrayType $arrayType, Type $columnType, Type $indexType, Scope $scope): ?Type { $builder = ConstantArrayTypeBuilder::createEmpty(); + if ($arrayType->isKeyOrderKnown()) { + $builder->makeKeyOrderKnown(); + } + $renumberedValueTypes = []; + $renumberedOptional = []; + $hasKeyedRow = false; + $hasIntegerKeyedRow = false; foreach ($arrayType->getValueTypes() as $i => $iterableValueType) { [$valueType, $certainty] = $this->getOffsetOrProperty($iterableValueType, $columnType, $scope); @@ -107,10 +114,34 @@ public function handleConstantArray(ConstantArrayType $arrayType, Type $columnTy if ($keyType !== null) { $keyType = $this->castToArrayKeyType($keyType, $scope); + $hasKeyedRow = true; + $hasIntegerKeyedRow = $hasIntegerKeyedRow || !$keyType->isInteger()->no(); + } elseif (!$arrayType->isKeyOrderKnown()) { + // the rows numbered by their positions may come in any order + $renumberedValueTypes[] = $valueType; + $renumberedOptional[] = $arrayType->isOptionalKey($i); + continue; } $builder->setOffsetValueType($keyType, $valueType, $arrayType->isOptionalKey($i)); } + if ($renumberedValueTypes !== []) { + if (!$hasKeyedRow) { + // every row is numbered by its position, so the rows come in the order of their values + return $this->handleConstantArray($arrayType->getValuesInKeyOrder(), $columnType, $indexType, $scope); + } + if ($hasIntegerKeyedRow) { + // the numbers continue after the integer keys of the rows that come before them + return null; + } + + // each of the numbers holds any of their values + $renumberedValueType = TypeCombinator::union(...$renumberedValueTypes); + foreach ($renumberedOptional as $optional) { + $builder->setOffsetValueType(null, $renumberedValueType, $optional); + } + } + if ($arrayType->isUnsealed()->yes()) { $unsealedTypes = $arrayType->getUnsealedTypes(); if ($unsealedTypes !== null) { @@ -135,6 +166,11 @@ public function handleConstantArray(ConstantArrayType $arrayType, Type $columnTy $unsealedKey = $unsealedTypes[0]; } + if ($renumberedValueTypes !== [] && !$unsealedKey->isInteger()->no()) { + // the numbers continue after the integer keys of the extra rows that come before them + return null; + } + $builder->makeUnsealed($unsealedKey, $unsealedValueType); } } diff --git a/src/Type/Php/ArrayCombineHelper.php b/src/Type/Php/ArrayCombineHelper.php index d4744cfe025..8e2f554b9e3 100644 --- a/src/Type/Php/ArrayCombineHelper.php +++ b/src/Type/Php/ArrayCombineHelper.php @@ -44,8 +44,9 @@ public function getReturnAndThrowType(Expr $firstArg, Expr $secondArg, Scope $sc foreach ($constantKeysArrays as $k => $constantKeysArray) { $constantValueArrays = $constantValuesArrays[$k]; - $keyTypes = $constantKeysArray->getValueTypes(); - $valueTypes = $constantValueArrays->getValueTypes(); + // the arrays pair their values in the order they have them + $keyTypes = $constantKeysArray->getValuesInKeyOrder()->getValueTypes(); + $valueTypes = $constantValueArrays->getValuesInKeyOrder()->getValueTypes(); if (count($keyTypes) !== count($valueTypes)) { return [new NeverType(), TrinaryLogic::createYes()]; @@ -57,6 +58,7 @@ public function getReturnAndThrowType(Expr $firstArg, Expr $secondArg, Scope $sc } $builder = ConstantArrayTypeBuilder::createEmpty(); + $builder->makeKeyOrderKnown(); foreach ($keyTypes as $i => $keyType) { if (!array_key_exists($i, $valueTypes)) { $results = []; diff --git a/src/Type/Php/ArrayFillFunctionReturnTypeExtension.php b/src/Type/Php/ArrayFillFunctionReturnTypeExtension.php index a8a0270120f..520bc346254 100644 --- a/src/Type/Php/ArrayFillFunctionReturnTypeExtension.php +++ b/src/Type/Php/ArrayFillFunctionReturnTypeExtension.php @@ -61,6 +61,7 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection, && $numberType->getValue() <= self::MAX_SIZE_USE_CONSTANT_ARRAY ) { $arrayBuilder = ConstantArrayTypeBuilder::createEmpty(); + $arrayBuilder->makeKeyOrderKnown(); $nextIndex = $startIndexType->getValue(); $overflows = false; for ($i = 0; $i < $numberType->getValue(); $i++) { diff --git a/src/Type/Php/ArrayFilterFunctionReturnTypeHelper.php b/src/Type/Php/ArrayFilterFunctionReturnTypeHelper.php index 97680958451..dcd7e835119 100644 --- a/src/Type/Php/ArrayFilterFunctionReturnTypeHelper.php +++ b/src/Type/Php/ArrayFilterFunctionReturnTypeHelper.php @@ -164,6 +164,9 @@ private function filterByTruthyValue(Scope $scope, Error|Variable|null $itemVar, $results = []; foreach ($constantArrays as $constantArray) { $builder = ConstantArrayTypeBuilder::createEmpty(); + if ($constantArray->isKeyOrderKnown()) { + $builder->makeKeyOrderKnown(); + } $optionalKeys = $constantArray->getOptionalKeys(); foreach ($constantArray->getKeyTypes() as $i => $keyType) { $itemType = $constantArray->getValueTypes()[$i]; diff --git a/src/Type/Php/ArrayFirstLastDynamicReturnTypeExtension.php b/src/Type/Php/ArrayFirstLastDynamicReturnTypeExtension.php index 859f36f1f02..d6b0f8dcc28 100644 --- a/src/Type/Php/ArrayFirstLastDynamicReturnTypeExtension.php +++ b/src/Type/Php/ArrayFirstLastDynamicReturnTypeExtension.php @@ -45,12 +45,16 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection, switch ($functionReflection->getName()) { case 'array_key_first': + $resultType = $argType->getFirstIterableKeyType(); + break; case 'array_key_last': - $resultType = $argType->getIterableKeyType(); + $resultType = $argType->getLastIterableKeyType(); break; case 'array_first': + $resultType = $argType->getFirstIterableValueType(); + break; case 'array_last': - $resultType = $argType->getIterableValueType(); + $resultType = $argType->getLastIterableValueType(); break; default: throw new ShouldNotHappenException(); diff --git a/src/Type/Php/ArrayMergeFunctionDynamicReturnTypeExtension.php b/src/Type/Php/ArrayMergeFunctionDynamicReturnTypeExtension.php index c0dc5f0db46..cd504894f24 100644 --- a/src/Type/Php/ArrayMergeFunctionDynamicReturnTypeExtension.php +++ b/src/Type/Php/ArrayMergeFunctionDynamicReturnTypeExtension.php @@ -24,6 +24,7 @@ use PHPStan\Type\Type; use PHPStan\Type\TypeCombinator; use PHPStan\Type\TypeUtils; +use function array_map; use function count; use function in_array; use function is_int; @@ -80,10 +81,25 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection, if ($allConstant->yes()) { $newArrayBuilder = ConstantArrayTypeBuilder::createEmpty(); + $newArrayBuilder->makeKeyOrderKnown(); $unsealed = null; foreach ($argTypes as $argIndex => $argType) { $isOptionalArg = in_array($argIndex, $optionalArgTypes, true); + $constantArrays = $argType->getConstantArrays(); + $renumberedArrays = array_map(static fn (ConstantArrayType $array): ConstantArrayType => $array->inRenumberingOrder(), $constantArrays); + if ($renumberedArrays !== $constantArrays) { + // the integer keys are renumbered in the order the array has them + $argType = TypeCombinator::union(...$renumberedArrays); + } + foreach ($renumberedArrays as $renumberedArray) { + if ($renumberedArray->isKeyOrderKnown()) { + continue; + } + + $newArrayBuilder->forgetKeyOrder(); + } + /** @var array $keyTypes */ $keyTypes = []; foreach ($argType->getConstantArrays() as $constantArray) { diff --git a/src/Type/Php/ArrayPointerFunctionsDynamicReturnTypeExtension.php b/src/Type/Php/ArrayPointerFunctionsDynamicReturnTypeExtension.php index a0a8019d061..79fde3e4623 100644 --- a/src/Type/Php/ArrayPointerFunctionsDynamicReturnTypeExtension.php +++ b/src/Type/Php/ArrayPointerFunctionsDynamicReturnTypeExtension.php @@ -46,8 +46,8 @@ public function getTypeFromFunctionCall( } $itemType = $functionReflection->getName() === 'reset' - ? $argType->getIterableValueType() - : $argType->getIterableValueType(); + ? $argType->getFirstIterableValueType() + : $argType->getLastIterableValueType(); if ($iterableAtLeastOnce->yes()) { return $itemType; } diff --git a/src/Type/Php/ArrayPopFunctionReturnTypeExtension.php b/src/Type/Php/ArrayPopFunctionReturnTypeExtension.php index 36ae85d4317..bb0b108c549 100644 --- a/src/Type/Php/ArrayPopFunctionReturnTypeExtension.php +++ b/src/Type/Php/ArrayPopFunctionReturnTypeExtension.php @@ -33,7 +33,7 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection, return new NullType(); } - $itemType = $argType->getIterableValueType(); + $itemType = $argType->getLastIterableValueType(); if ($iterableAtLeastOnce->yes()) { return $itemType; } diff --git a/src/Type/Php/ArrayReplaceFunctionReturnTypeExtension.php b/src/Type/Php/ArrayReplaceFunctionReturnTypeExtension.php index 0bdd4a6ece4..f51e065880c 100644 --- a/src/Type/Php/ArrayReplaceFunctionReturnTypeExtension.php +++ b/src/Type/Php/ArrayReplaceFunctionReturnTypeExtension.php @@ -80,6 +80,18 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection, if ($allConstant->yes()) { $newArrayBuilder = ConstantArrayTypeBuilder::createEmpty(); + // the keys come in the order of the arrays, each one only where it first appears + $keyOrderKnown = true; + foreach ($argTypes as $argType) { + $constantArrays = $argType->getConstantArrays(); + if (count($constantArrays) === 1 && $constantArrays[0]->isKeyOrderKnown()) { + continue; + } + $keyOrderKnown = false; + } + if ($keyOrderKnown) { + $newArrayBuilder->makeKeyOrderKnown(); + } $unsealed = null; foreach ($argTypes as $argIndex => $argType) { diff --git a/src/Type/Php/ArrayShiftFunctionReturnTypeExtension.php b/src/Type/Php/ArrayShiftFunctionReturnTypeExtension.php index 51e2a534ec2..3679aaed46f 100644 --- a/src/Type/Php/ArrayShiftFunctionReturnTypeExtension.php +++ b/src/Type/Php/ArrayShiftFunctionReturnTypeExtension.php @@ -33,7 +33,7 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection, return new NullType(); } - $itemType = $argType->getIterableValueType(); + $itemType = $argType->getFirstIterableValueType(); if ($iterableAtLeastOnce->yes()) { return $itemType; } diff --git a/src/Type/Php/CompactFunctionReturnTypeExtension.php b/src/Type/Php/CompactFunctionReturnTypeExtension.php index 497668c7f6f..45eadfe75b8 100644 --- a/src/Type/Php/CompactFunctionReturnTypeExtension.php +++ b/src/Type/Php/CompactFunctionReturnTypeExtension.php @@ -47,6 +47,7 @@ public function getTypeFromFunctionCall( } $array = ConstantArrayTypeBuilder::createEmpty(); + $array->makeKeyOrderKnown(); foreach ($args as $arg) { $type = $scope->getType($arg->value); $constantStrings = $this->findConstantStrings($type); diff --git a/src/Type/Php/ExplodeFunctionDynamicReturnTypeExtension.php b/src/Type/Php/ExplodeFunctionDynamicReturnTypeExtension.php index 0784ae18710..e77afa9b85a 100644 --- a/src/Type/Php/ExplodeFunctionDynamicReturnTypeExtension.php +++ b/src/Type/Php/ExplodeFunctionDynamicReturnTypeExtension.php @@ -210,6 +210,7 @@ private function createConstantSplitType(Type $delimiterType, Type $stringType, } $builder = ConstantArrayTypeBuilder::createEmpty(); + $builder->makeKeyOrderKnown(); foreach ($items as $i => $item) { $builder->setOffsetValueType(new ConstantIntegerType($i), new ConstantStringType($item)); } @@ -305,6 +306,7 @@ private function isMinusOneLimit(?Type $limitType): bool private function createSingleElementSplitType(Type $valueType): Type { $builder = ConstantArrayTypeBuilder::createEmpty(); + $builder->makeKeyOrderKnown(); $builder->setOffsetValueType(new ConstantIntegerType(0), $valueType); return $builder->getArray(); @@ -318,6 +320,7 @@ private function createSingleElementSplitType(Type $valueType): Type private function createGuaranteedSplitType(Type $valueType, ?Type $limitType): Type { $builder = ConstantArrayTypeBuilder::createEmpty(); + $builder->makeKeyOrderKnown(); $builder->setOffsetValueType(new ConstantIntegerType(0), $valueType); $builder->setOffsetValueType(new ConstantIntegerType(1), $valueType); diff --git a/src/Type/Php/ImplodeFunctionReturnTypeExtension.php b/src/Type/Php/ImplodeFunctionReturnTypeExtension.php index 22ca6751eb9..315bf34df00 100644 --- a/src/Type/Php/ImplodeFunctionReturnTypeExtension.php +++ b/src/Type/Php/ImplodeFunctionReturnTypeExtension.php @@ -66,7 +66,7 @@ private function implode(Type $arrayType, Type $separatorType): Type $result = []; foreach ($separatorType->getConstantStrings() as $separator) { foreach ($arrayType->getConstantArrays() as $constantArray) { - $constantType = $this->inferConstantType($constantArray, $separator, $isNonEmpty); + $constantType = $this->inferConstantType($constantArray->getValuesInKeyOrder(), $separator, $isNonEmpty); if ($constantType !== null) { $result[] = $constantType; continue; diff --git a/src/Type/Php/PregSplitDynamicReturnTypeExtension.php b/src/Type/Php/PregSplitDynamicReturnTypeExtension.php index fe582a38585..fa5ceed0d85 100644 --- a/src/Type/Php/PregSplitDynamicReturnTypeExtension.php +++ b/src/Type/Php/PregSplitDynamicReturnTypeExtension.php @@ -115,6 +115,7 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection, } $arrayTypeBuilder = ConstantArrayTypeBuilder::createEmpty(); + $arrayTypeBuilder->makeKeyOrderKnown(); $arrayTypeBuilder->setOffsetValueType( new ConstantIntegerType(0), $returnStringType, diff --git a/src/Type/Php/RangeFunctionReturnTypeExtension.php b/src/Type/Php/RangeFunctionReturnTypeExtension.php index 66dd404d043..128e883339c 100644 --- a/src/Type/Php/RangeFunctionReturnTypeExtension.php +++ b/src/Type/Php/RangeFunctionReturnTypeExtension.php @@ -140,6 +140,7 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection, } $arrayBuilder = ConstantArrayTypeBuilder::createEmpty(); + $arrayBuilder->makeKeyOrderKnown(); foreach ($rangeValues as $value) { $arrayBuilder->setOffsetValueType(null, $scope->getTypeFromValue($value)); } diff --git a/src/Type/Php/RegexArrayShapeMatcher.php b/src/Type/Php/RegexArrayShapeMatcher.php index 7198b68c7d6..b3c0d809913 100644 --- a/src/Type/Php/RegexArrayShapeMatcher.php +++ b/src/Type/Php/RegexArrayShapeMatcher.php @@ -194,6 +194,7 @@ private function matchRegex(string $regex, ?int $flags, TrinaryLogic $wasMatched if (!$this->containsUnmatchedAsNull($flags, $matchesAll)) { // positive match has a subject but not any capturing group $builder = ConstantArrayTypeBuilder::createEmpty(); + $builder->makeKeyOrderKnown(); $builder->setOffsetValueType(new ConstantIntegerType(0), $this->createSubjectValueType($subjectBaseType, $flags, $matchesAll, $wasMatched)); $combiType = TypeCombinator::union( @@ -257,6 +258,7 @@ private function matchRegex(string $regex, ?int $flags, TrinaryLogic $wasMatched ) { // positive match has a subject but not any capturing group $builder = ConstantArrayTypeBuilder::createEmpty(); + $builder->makeKeyOrderKnown(); $builder->setOffsetValueType(new ConstantIntegerType(0), $this->createSubjectValueType($subjectBaseType, $flags, $matchesAll, $wasMatched)); $combiTypes[] = $builder->getArray(); @@ -293,6 +295,7 @@ private function buildArrayType( { $forceList = count($markVerbs) === 0; $builder = ConstantArrayTypeBuilder::createEmpty(); + $builder->makeKeyOrderKnown(); // first item in matches contains the overall match. $builder->setOffsetValueType( @@ -551,6 +554,7 @@ private function getValueType(Type $baseType, int $flags, bool $matchesAll): Typ if ($this->containsOffsetCapture($flags)) { $builder = ConstantArrayTypeBuilder::createEmpty(); + $builder->makeKeyOrderKnown(); $builder->setOffsetValueType( new ConstantIntegerType(0), diff --git a/src/Type/Php/SscanfFunctionDynamicReturnTypeExtension.php b/src/Type/Php/SscanfFunctionDynamicReturnTypeExtension.php index ab48c2f31b6..bbe22f4a5a9 100644 --- a/src/Type/Php/SscanfFunctionDynamicReturnTypeExtension.php +++ b/src/Type/Php/SscanfFunctionDynamicReturnTypeExtension.php @@ -49,6 +49,7 @@ public function getTypeFromFunctionCall( if (preg_match_all('/%(\d*)(\[[^\]]+\]|[cdeEfosux]{1})/', $formatType->getValue(), $matches) > 0) { $arrayBuilder = ConstantArrayTypeBuilder::createEmpty(); + $arrayBuilder->makeKeyOrderKnown(); for ($i = 0; $i < count($matches[0]); $i++) { $length = $matches[1][$i]; diff --git a/src/Type/StaticType.php b/src/Type/StaticType.php index 5db147e58c9..4adeb066250 100644 --- a/src/Type/StaticType.php +++ b/src/Type/StaticType.php @@ -437,12 +437,12 @@ public function getIterableKeyType(): Type public function getFirstIterableKeyType(): Type { - return $this->getStaticObjectType()->getIterableKeyType(); + return $this->getStaticObjectType()->getFirstIterableKeyType(); } public function getLastIterableKeyType(): Type { - return $this->getStaticObjectType()->getIterableKeyType(); + return $this->getStaticObjectType()->getLastIterableKeyType(); } public function getIterableValueType(): Type @@ -452,12 +452,12 @@ public function getIterableValueType(): Type public function getFirstIterableValueType(): Type { - return $this->getStaticObjectType()->getIterableValueType(); + return $this->getStaticObjectType()->getFirstIterableValueType(); } public function getLastIterableValueType(): Type { - return $this->getStaticObjectType()->getIterableValueType(); + return $this->getStaticObjectType()->getLastIterableValueType(); } public function isOffsetAccessible(): TrinaryLogic diff --git a/src/Type/Traits/DelegatingTypeTrait.php b/src/Type/Traits/DelegatingTypeTrait.php index 7c80136824f..8ce3852a321 100644 --- a/src/Type/Traits/DelegatingTypeTrait.php +++ b/src/Type/Traits/DelegatingTypeTrait.php @@ -192,12 +192,12 @@ public function getIterableKeyType(): Type public function getFirstIterableKeyType(): Type { - return $this->getDelegate()->getIterableKeyType(); + return $this->getDelegate()->getFirstIterableKeyType(); } public function getLastIterableKeyType(): Type { - return $this->getDelegate()->getIterableKeyType(); + return $this->getDelegate()->getLastIterableKeyType(); } public function getIterableValueType(): Type @@ -207,12 +207,12 @@ public function getIterableValueType(): Type public function getFirstIterableValueType(): Type { - return $this->getDelegate()->getIterableValueType(); + return $this->getDelegate()->getFirstIterableValueType(); } public function getLastIterableValueType(): Type { - return $this->getDelegate()->getIterableValueType(); + return $this->getDelegate()->getLastIterableValueType(); } public function isArray(): TrinaryLogic diff --git a/src/Type/Type.php b/src/Type/Type.php index c9a19b08005..85c7e520fd6 100644 --- a/src/Type/Type.php +++ b/src/Type/Type.php @@ -188,18 +188,18 @@ public function getArraySize(): Type; */ public function getIterableKeyType(): Type; - /** @deprecated use getIterableKeyType */ + /** The type of the first key; the union of the keys when their order is not known. */ public function getFirstIterableKeyType(): Type; - /** @deprecated use getIterableKeyType */ + /** The type of the last key; the union of the keys when their order is not known. */ public function getLastIterableKeyType(): Type; public function getIterableValueType(): Type; - /** @deprecated use getIterableValueType */ + /** The type of the first value; the union of the values when the order of the keys is not known. */ public function getFirstIterableValueType(): Type; - /** @deprecated use getIterableValueType */ + /** The type of the last value; the union of the values when the order of the keys is not known. */ public function getLastIterableValueType(): Type; public function isArray(): TrinaryLogic; diff --git a/src/Type/UnionType.php b/src/Type/UnionType.php index fc5ef6c89a3..3a4c2f74e8e 100644 --- a/src/Type/UnionType.php +++ b/src/Type/UnionType.php @@ -939,12 +939,12 @@ public function getIterableKeyType(): Type public function getFirstIterableKeyType(): Type { - return $this->unionTypes(static fn (Type $type): Type => $type->getIterableKeyType()); + return $this->unionTypes(static fn (Type $type): Type => $type->getFirstIterableKeyType()); } public function getLastIterableKeyType(): Type { - return $this->unionTypes(static fn (Type $type): Type => $type->getIterableKeyType()); + return $this->unionTypes(static fn (Type $type): Type => $type->getLastIterableKeyType()); } public function getIterableValueType(): Type @@ -954,12 +954,12 @@ public function getIterableValueType(): Type public function getFirstIterableValueType(): Type { - return $this->unionTypes(static fn (Type $type): Type => $type->getIterableValueType()); + return $this->unionTypes(static fn (Type $type): Type => $type->getFirstIterableValueType()); } public function getLastIterableValueType(): Type { - return $this->unionTypes(static fn (Type $type): Type => $type->getIterableValueType()); + return $this->unionTypes(static fn (Type $type): Type => $type->getLastIterableValueType()); } public function isArray(): TrinaryLogic diff --git a/tests/PHPStan/Analyser/NoBleedingEdgeTypeInferenceTest.php b/tests/PHPStan/Analyser/NoBleedingEdgeTypeInferenceTest.php index 03ee11eaf28..5ddf0a9608d 100644 --- a/tests/PHPStan/Analyser/NoBleedingEdgeTypeInferenceTest.php +++ b/tests/PHPStan/Analyser/NoBleedingEdgeTypeInferenceTest.php @@ -18,10 +18,12 @@ public static function dataAsserts(): iterable yield from self::gatherAssertTypes(__DIR__ . '/data/bug-15749.php'); yield from self::gatherAssertTypes(__DIR__ . '/data/bug-15760.php'); yield from self::gatherAssertTypes(__DIR__ . '/nsrt/bug-15780.php'); - yield from self::gatherAssertTypes(__DIR__ . '/nsrt/bug-15820.php'); + // a list that names its keys describes itself as list{...} only with bleeding edge + yield from self::gatherAssertTypes(__DIR__ . '/data/bug-15820-no-bleeding-edge.php'); yield from self::gatherAssertTypes(__DIR__ . '/nsrt/bug-15860.php'); yield from self::gatherAssertTypes(__DIR__ . '/nsrt/bug-15869.php'); - yield from self::gatherAssertTypes(__DIR__ . '/nsrt/bug-15870.php'); + // a shape whose keys come in any order lists them in the order the merges building it come to + yield from self::gatherAssertTypes(__DIR__ . '/data/bug-15870-no-bleeding-edge.php'); yield from self::gatherAssertTypes(__DIR__ . '/data/dependent-array-unions.php'); } @@ -38,4 +40,12 @@ public function testAsserts( $this->assertFileAsserts($assertType, $file, ...$args); } + public function testCountOfShapeThatCanHaveKeysItDoesNotList(): void + { + // analysed here, not in a data provider, so that mutation testing counts the code it covers + foreach (self::gatherAssertTypes(__DIR__ . '/data/count-shape-no-bleeding-edge.php') as $args) { + $this->assertFileAsserts(...$args); + } + } + } diff --git a/tests/PHPStan/Analyser/data/bug-15820-no-bleeding-edge.php b/tests/PHPStan/Analyser/data/bug-15820-no-bleeding-edge.php new file mode 100644 index 00000000000..750cd84ee2a --- /dev/null +++ b/tests/PHPStan/Analyser/data/bug-15820-no-bleeding-edge.php @@ -0,0 +1,27 @@ + ['reasonKey' => 'signup', 'tokens' => ['s0', 's1', 's2', 's3', 's4', 's5', 's6', 's7', 's8', 's9', 's10', 's11', 's12', 's13', 's14', 's15', 's16', 's17', 's18', 's19', 's20', 's21', 's22', 's23', 's24', 's25', 's26', 's27', 's28', 's29', 's30', 's31', 's32', 's33', 's34', 's35', 's36', 's37', 's38', 's39', 's40', 's41', 's42', 's43', 's44', 's45', 's46', 's47', 's48', 's49', 's50', 's51', 's52', 's53', 's54', 's55', 's56', 's57', 's58', 's59', 's60', 's61', 's62', 's63', 's64', 's65', 's66', 's67', 's68', 's69', 's70', 's71', 's72', 's73', 's74', 's75', 's76', 's77', 's78', 's79', 's80', 's81', 's82', 's83', 's84', 's85']], + 'demo' => ['reasonKey' => 'demo', 'eventName' => 'quote-request', 'tokens' => ['d0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'd10', 'd11', 'd12', 'd13', 'd14', 'd15', 'd16', 'd17', 'd18', 'd19', 'd20', 'd21', 'd22', 'd23', 'd24', 'd25', 'd26', 'd27', 'd28', 'd29', 'd30', 'd31', 'd32', 'd33', 'd34', 'd35', 'd36', 'd37', 'd38', 'd39', 'd40', 'd41', 'd42', 'd43', 'd44', 'd45', 'd46', 'd47', 'd48', 'd49', 'd50', 'd51', 'd52', 'd53', 'd54', 'd55', 'd56', 'd57', 'd58', 'd59', 'd60', 'd61', 'd62', 'd63', 'd64', 'd65', 'd66', 'd67', 'd68', 'd69', 'd70', 'd71', 'd72', 'd73', 'd74', 'd75', 'd76', 'd77', 'd78', 'd79', 'd80', 'd81', 'd82', 'd83', 'd84', 'd85']], + 'contact' => ['reasonKey' => 'contact', 'tokens' => ['c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'c10', 'c11', 'c12', 'c13', 'c14', 'c15', 'c16', 'c17', 'c18', 'c19', 'c20', 'c21', 'c22', 'c23', 'c24', 'c25', 'c26', 'c27', 'c28', 'c29', 'c30', 'c31', 'c32', 'c33', 'c34', 'c35', 'c36', 'c37', 'c38', 'c39', 'c40', 'c41', 'c42', 'c43', 'c44', 'c45', 'c46', 'c47', 'c48', 'c49', 'c50', 'c51', 'c52', 'c53', 'c54', 'c55', 'c56', 'c57', 'c58', 'c59', 'c60', 'c61', 'c62', 'c63', 'c64', 'c65', 'c66', 'c67', 'c68', 'c69', 'c70', 'c71', 'c72', 'c73', 'c74', 'c75', 'c76', 'c77', 'c78', 'c79', 'c80', 'c81', 'c82', 'c83', 'c84', 'c85']], + ]; + + public function eventName(string $category): ?string + { + $definition = self::CATEGORIES[$category]; + assertType("array{0: 'reasonKey', 1: 'eventName'|'tokens', 2?: 'tokens'}", array_keys($definition)); + if (isset($definition['eventName'])) { + assertType("'quote-request'", $definition['eventName']); + return $definition['eventName']; + } + + return null; + } +} + diff --git a/tests/PHPStan/Analyser/data/bug-15870-no-bleeding-edge.php b/tests/PHPStan/Analyser/data/bug-15870-no-bleeding-edge.php new file mode 100644 index 00000000000..e33ed5e13d0 --- /dev/null +++ b/tests/PHPStan/Analyser/data/bug-15870-no-bleeding-edge.php @@ -0,0 +1,41 @@ +> $messages + * @param list $parts + */ +function parse(string $name, array $messages, array $parts, string $line, int $t): void +{ + $data['header'][0]['name'] = $name; + for ($m = 0; $m < count($messages); $m++) { + $data['message'][$m]['header']['_pointer'] = 'header[0][id]'; + for ($l = 0; $l < count($messages[$m]); $l++) { + switch ($messages[$m][$l]) { + case 'a': + $data['message'][$m]['reference'] = trim($line); + $data['message'][$m]['account'] = trim($line); + case 'b': + $data['message'][$m]['number'] = trim($parts[0]); + $data['message'][$m]['sequence'] = trim($parts[1] ?? ''); + case 'c': + if (!isset($data['message'][$m]['startSign'])) { + $data['message'][$m]['startSign'] = trim($line); + $data['message'][$m]['startDate'] = trim($line); + $data['message'][$m]['startCurrency'] = trim($line); + $data['message'][$m]['startBalance'] = trim($line); + } + assertType("array{header: array{array{name: string}}, message: non-empty-array, array{header?: array{_pointer: 'header[0][id]'}, endBalance?: string, startSign?: string, startDate?: string, startCurrency?: string, startBalance?: string, number?: string, sequence?: string, reference?: string, account?: string}>, transaction?: non-empty-array}", $data); + $data['transaction'][$t]['description'] .= trim($line); + case 'd': + $data['message'][$m]['endBalance'] = trim($line); + } + } + assertType("array{header: array{array{name: string}}, message: non-empty-array, array{header?: array{_pointer: 'header[0][id]'}, endBalance?: string, startSign?: string, startDate?: string, startCurrency?: string, startBalance?: string, number?: string, sequence?: string, reference?: string, account?: string}>, transaction?: non-empty-array}", $data); + foreach ($data['transaction'] as $transaction) { + } + } +} diff --git a/tests/PHPStan/Analyser/data/count-shape-no-bleeding-edge.php b/tests/PHPStan/Analyser/data/count-shape-no-bleeding-edge.php new file mode 100644 index 00000000000..e72f2998e3c --- /dev/null +++ b/tests/PHPStan/Analyser/data/count-shape-no-bleeding-edge.php @@ -0,0 +1,16 @@ + 0, 17 => 1, 'b' => 2]; assertType('array{array{0, 1}, array{2}}', array_chunk($arr, 2)); assertType('array{array{a: 0, 17: 1}, array{b: 2}}', array_chunk($arr, 2, true)); assertType('array{array{0}, array{1}, array{2}}', array_chunk($arr, 1)); @@ -34,12 +34,24 @@ public function constantArrays(array $arr): void public function constantArraysWithOptionalKeys(array $arr): void { - /** @var array{a: 0, b?: 1, c: 2} $arr */ + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['b']); + } assertType('array{array{a: 0, b?: 1, c?: 2}, array{c?: 2}}', array_chunk($arr, 2, true)); assertType('array{array{a: 0, b?: 1, c: 2}}', array_chunk($arr, 3, true)); assertType('array{array{a: 0}, array{b?: 1, c?: 2}, array{c?: 2}}', array_chunk($arr, 1, true)); - /** @var array{a?: 0, b?: 1, c?: 2} $arr */ + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['a']); + } + if (rand(0, 1)) { + unset($arr['b']); + } + if (rand(0, 1)) { + unset($arr['c']); + } assertType('array{array{a?: 0, b?: 1, c?: 2}, array{c?: 2}}', array_chunk($arr, 2, true)); } @@ -48,10 +60,13 @@ public function constantArraysWithOptionalKeys(array $arr): void * @param 2|3 $positiveUnion */ public function chunkUnionTypeLength(array $arr, $positiveRange, $positiveUnion) { - /** @var array{a: 0, b?: 1, c: 2} $arr */ - assertType('array{array{0: 0, 1: 1|2, 2?: 2}}|array{list{0: 0, 1?: 1|2, 2?: 2}, array{0?: 2}}', array_chunk($arr, $positiveRange)); + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['b']); + } + assertType('array{list{0: 0, 1: 1|2, 2?: 2}}|array{list{0: 0, 1?: 1|2, 2?: 2}, array{0?: 2}}', array_chunk($arr, $positiveRange)); assertType('array{array{a: 0, b?: 1, c: 2}}|array{array{a: 0, b?: 1, c?: 2}, array{c?: 2}}', array_chunk($arr, $positiveRange, true)); - assertType('array{array{0: 0, 1: 1|2, 2?: 2}}|array{list{0: 0, 1?: 1|2, 2?: 2}, array{0?: 2}}', array_chunk($arr, $positiveUnion)); + assertType('array{list{0: 0, 1: 1|2, 2?: 2}}|array{list{0: 0, 1?: 1|2, 2?: 2}, array{0?: 2}}', array_chunk($arr, $positiveUnion)); assertType('array{array{a: 0, b?: 1, c: 2}}|array{array{a: 0, b?: 1, c?: 2}, array{c?: 2}}', array_chunk($arr, $positiveUnion, true)); } @@ -69,8 +84,11 @@ public function lengthIntRanges(array $arr, int $positiveInt, int $bigger50) { * @param int<1, 5> $tooBig */ function testLimits(array $arr, int $oneToFour, int $tooBig) { - /** @var array{a: 0, b?: 1, c: 2, d: 3} $arr */ - assertType('array{array{0: 0, 1: 1|2, 2: 2|3, 3?: 3}}|array{array{0}, list{0?: 1|2, 1?: 2}, list{0?: 2|3, 1?: 3}, array{0?: 3}}|array{list{0: 0, 1: 1|2, 2?: 2|3, 3?: 3}, array{0?: 3}}|array{list{0: 0, 1?: 1|2, 2?: 2}, array{0: 2|3, 1?: 3}}', array_chunk($arr, $oneToFour)); + $arr = ['a' => 0, 'b' => 1, 'c' => 2, 'd' => 3]; + if (rand(0, 1)) { + unset($arr['b']); + } + assertType('array{array{0}, list{0?: 1|2, 1?: 2}, list{0?: 2|3, 1?: 3}, array{0?: 3}}|array{list{0: 0, 1: 1|2, 2: 2|3, 3?: 3}}|array{list{0: 0, 1: 1|2, 2?: 2|3, 3?: 3}, array{0?: 3}}|array{list{0: 0, 1?: 1|2, 2?: 2}, list{0: 2|3, 1?: 3}}', array_chunk($arr, $oneToFour)); assertType('non-empty-list>', array_chunk($arr, $tooBig)); } diff --git a/tests/PHPStan/Analyser/nsrt/array-column.php b/tests/PHPStan/Analyser/nsrt/array-column.php index ca2a819d77a..dd2bcb11ee4 100644 --- a/tests/PHPStan/Analyser/nsrt/array-column.php +++ b/tests/PHPStan/Analyser/nsrt/array-column.php @@ -158,16 +158,17 @@ public function testConstantArray12(array $array): void /** @param array{0?: array{column: 'foo1', key: 'bar1'}, 1?: array{column: 'foo2', key: 'bar2'}} $array */ public function testConstantArray13(array $array): void { - assertType("list{0?: 'foo1'|'foo2', 1?: 'foo2'}", array_column($array, 'column')); - assertType("list{0?: 'foo1'|'foo2', 1?: 'foo2'}", array_column($array, 'column', null)); + // the rows can come in any order, so either column value can come second + assertType("list{0?: 'foo1'|'foo2', 1?: 'foo1'|'foo2'}", array_column($array, 'column')); + assertType("list{0?: 'foo1'|'foo2', 1?: 'foo1'|'foo2'}", array_column($array, 'column', null)); assertType("array{bar1?: 'foo1', bar2?: 'foo2'}", array_column($array, 'column', 'key')); } /** @param array{0?: array{column: 'foo1', key: 'bar1'}, 1: array{column: 'foo2', key: 'bar2'}} $array */ public function testConstantArray14(array $array): void { - assertType("array{0: 'foo1'|'foo2', 1?: 'foo2'}", array_column($array, 'column')); - assertType("array{0: 'foo1'|'foo2', 1?: 'foo2'}", array_column($array, 'column', null)); + assertType("list{0: 'foo1'|'foo2', 1?: 'foo1'|'foo2'}", array_column($array, 'column')); + assertType("list{0: 'foo1'|'foo2', 1?: 'foo1'|'foo2'}", array_column($array, 'column', null)); assertType("array{bar1?: 'foo1', bar2: 'foo2'}", array_column($array, 'column', 'key')); } diff --git a/tests/PHPStan/Analyser/nsrt/array-combine-php8.php b/tests/PHPStan/Analyser/nsrt/array-combine-php8.php index ee378f0ad8f..5e4f95d4b16 100644 --- a/tests/PHPStan/Analyser/nsrt/array-combine-php8.php +++ b/tests/PHPStan/Analyser/nsrt/array-combine-php8.php @@ -189,7 +189,7 @@ function onlyKeysUnsealed(array $keys) /** * @param list<'1'|'2'> $constantIntStrings - * @param array{0: '1', 1: '2'} $sealedIntStrings + * @param array{'1', '2'} $sealedIntStrings */ function withConstantIntStringKeys(array $constantIntStrings, array $sealedIntStrings): void { diff --git a/tests/PHPStan/Analyser/nsrt/array-functions.php b/tests/PHPStan/Analyser/nsrt/array-functions.php index 4cefe03a2c9..18df06a7ca3 100644 --- a/tests/PHPStan/Analyser/nsrt/array-functions.php +++ b/tests/PHPStan/Analyser/nsrt/array-functions.php @@ -270,11 +270,11 @@ assertType('array{foo: \'banana\', bar: \'banana\', baz: \'banana\', lorem: \'banana\'}|array{foo: \'banana\', bar: \'banana\'}', array_fill_keys($conditionalArray, 'banana')); assertType('array{foo: stdClass, bar: stdClass, baz: stdClass, lorem: stdClass}|array{foo: stdClass, bar: stdClass}', array_map(function (): \stdClass {}, $conditionalKeysArray)); $stringKeysCopy1 = $stringKeys; -assertType('\'foo\'|stdClass', array_pop($stringKeysCopy1)); +assertType('stdClass', array_pop($stringKeysCopy1)); assertType('non-empty-array&hasOffsetValue(\'baz\', stdClass)', $stdClassesWithIsset); assertType('stdClass', array_pop($stdClassesWithIsset)); $stringKeysCopy2 = $stringKeys; -assertType('\'foo\'|stdClass', array_shift($stringKeysCopy2)); +assertType('\'foo\'', array_shift($stringKeysCopy2)); assertType('int|null', array_pop($generalStringKeys)); assertType('int|null', array_shift($generalStringKeys)); assertType('null', array_pop([])); diff --git a/tests/PHPStan/Analyser/nsrt/array-keys-branches.php b/tests/PHPStan/Analyser/nsrt/array-keys-branches.php index 986ff618db4..ef373e978fe 100644 --- a/tests/PHPStan/Analyser/nsrt/array-keys-branches.php +++ b/tests/PHPStan/Analyser/nsrt/array-keys-branches.php @@ -56,7 +56,7 @@ function (array $generalArray) { assertType("array{i: 3, j: int, k: 2, l: 1, m: 5, key: DateTimeImmutable, n?: 'str'}", $array); assertType('non-empty-array&hasOffsetValue(\'key\', mixed~null)', $generalArray); assertType('mixed~null+DateTimeImmutable', $generalArray['key']); - assertType('array{0: \'foo\', 1: \'bar\', 2?: \'baz\'}', $arrayAppendedInIf); + assertType('list{0: \'foo\', 1: \'bar\', 2?: \'baz\'}', $arrayAppendedInIf); assertType('non-empty-list<\'bar\'|\'baz\'|\'foo\'>', $arrayAppendedInForeach); assertType('non-empty-array, literal-string&lowercase-string&non-falsy-string>', $anotherArrayAppendedInForeach); assertType('\'str\'', $array['n']); @@ -122,7 +122,7 @@ function (array $generalArray, array $xs) { assertType('array{i: (float|int), j: int, k: int<1, max>, l: 1, m: 5, key: DateTimeImmutable, n?: \'str\'}|array{i: 0, j: int, k: 0, l: 1, m: 5, key: DateTimeImmutable, n?: \'str\'}', $array); assertType('non-empty-array&hasOffsetValue(\'key\', mixed~null)', $generalArray); assertType('mixed~null+DateTimeImmutable', $generalArray['key']); - assertType('array{0: \'foo\', 1: \'bar\', 2?: \'baz\'}', $arrayAppendedInIf); + assertType('list{0: \'foo\', 1: \'bar\', 2?: \'baz\'}', $arrayAppendedInIf); assertType('non-empty-list<\'bar\'|\'baz\'|\'foo\'>', $arrayAppendedInForeach); assertType('non-empty-array, literal-string&lowercase-string&non-falsy-string>', $anotherArrayAppendedInForeach); assertType('\'str\'', $array['n']); diff --git a/tests/PHPStan/Analyser/nsrt/array-merge2.php b/tests/PHPStan/Analyser/nsrt/array-merge2.php index f0d86e61b6a..591d4cef647 100644 --- a/tests/PHPStan/Analyser/nsrt/array-merge2.php +++ b/tests/PHPStan/Analyser/nsrt/array-merge2.php @@ -7,12 +7,10 @@ class Foo { - /** - * @param array{foo: '1', bar: '2', lall: '3', 2: '2', 3: '3'} $array1 - * @param array{foo: '1', bar: '4', lall2: '3', 2: '4', 3: '6'} $array2 - */ - public function arrayMergeArrayShapes($array1, $array2): void + public function arrayMergeArrayShapes(): void { + $array1 = ['foo' => '1', 'bar' => '2', 'lall' => '3', 2 => '2', 3 => '3']; + $array2 = ['foo' => '1', 'bar' => '4', 'lall2' => '3', 2 => '4', 3 => '6']; assertType("array{foo: '1', bar: '2', lall: '3', 0: '2', 1: '3'}", array_merge($array1)); assertType("array{foo: '1', bar: '2', lall: '3', 0: '2', 1: '3'}", array_merge([], $array1)); assertType("array{foo: '1', bar: '2', lall: '3', 0: '2', 1: '3'}", array_merge($array1, [])); diff --git a/tests/PHPStan/Analyser/nsrt/array-pointer-functions.php b/tests/PHPStan/Analyser/nsrt/array-pointer-functions.php index 5dc5ae87af5..49d3f9b9fdf 100644 --- a/tests/PHPStan/Analyser/nsrt/array-pointer-functions.php +++ b/tests/PHPStan/Analyser/nsrt/array-pointer-functions.php @@ -38,8 +38,8 @@ public function doFoo(array $generalArray, $somethingElse) assertType('stdClass|false', reset($generalArray)); assertType('mixed', reset($somethingElse)); assertType('false', reset($emptyConstantArray)); - assertType('1|2', reset($constantArray)); - assertType('\'bar\'|\'baz\'|\'foo\'', reset($conditionalArray)); + assertType('1', reset($constantArray)); + assertType('\'baz\'|\'foo\'', reset($conditionalArray)); assertType('0|1|2', reset($constantArrayOptionalKeys1)); assertType('0|1|2', reset($constantArrayOptionalKeys2)); assertType('0|1|2', reset($constantArrayOptionalKeys3)); @@ -47,8 +47,8 @@ public function doFoo(array $generalArray, $somethingElse) assertType('stdClass|false', end($generalArray)); assertType('mixed', end($somethingElse)); assertType('false', end($emptyConstantArray)); - assertType('1|2', end($constantArray)); - assertType('\'bar\'|\'baz\'|\'foo\'', end($secondConditionalArray)); + assertType('2', end($constantArray)); + assertType('\'bar\'|\'baz\'', end($secondConditionalArray)); assertType('0|1|2', end($constantArrayOptionalKeys1)); assertType('0|1|2', end($constantArrayOptionalKeys2)); assertType('0|1|2', end($constantArrayOptionalKeys3)); diff --git a/tests/PHPStan/Analyser/nsrt/array-pop.php b/tests/PHPStan/Analyser/nsrt/array-pop.php index 971859d166d..3090813faeb 100644 --- a/tests/PHPStan/Analyser/nsrt/array-pop.php +++ b/tests/PHPStan/Analyser/nsrt/array-pop.php @@ -31,30 +31,48 @@ public function compoundTypes(array $arr): void public function constantArrays(array $arr): void { - /** @var array{a: 0, b: 1, c: 2} $arr */ - assertType('0|1|2', array_pop($arr)); + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + assertType('2', array_pop($arr)); assertType('array{a: 0, b: 1}', $arr); - /** @var array{} $arr */ + $arr = []; assertType('null', array_pop($arr)); assertType('array{}', $arr); } public function constantArraysWithOptionalKeys(array $arr): void { - /** @var array{a?: 0, b: 1, c: 2} $arr */ - assertType('0|1|2', array_pop($arr)); + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['a']); + } + assertType('2', array_pop($arr)); assertType('array{a?: 0, b: 1}', $arr); - /** @var array{a: 0, b?: 1, c: 2} $arr */ - assertType('0|1|2', array_pop($arr)); + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['b']); + } + assertType('2', array_pop($arr)); assertType('array{a: 0, b?: 1}', $arr); - /** @var array{a: 0, b: 1, c?: 2} $arr */ - assertType('0|1|2', array_pop($arr)); + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['c']); + } + assertType('1|2', array_pop($arr)); assertType('array{a: 0, b?: 1}', $arr); - /** @var array{a?: 0, b?: 1, c?: 2} $arr */ + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['a']); + } + if (rand(0, 1)) { + unset($arr['b']); + } + if (rand(0, 1)) { + unset($arr['c']); + } assertType('0|1|2|null', array_pop($arr)); assertType('array{a?: 0, b?: 1}', $arr); } diff --git a/tests/PHPStan/Analyser/nsrt/array-reverse.php b/tests/PHPStan/Analyser/nsrt/array-reverse.php index db05a1d57e2..110b13bb41f 100644 --- a/tests/PHPStan/Analyser/nsrt/array-reverse.php +++ b/tests/PHPStan/Analyser/nsrt/array-reverse.php @@ -23,11 +23,17 @@ public function normalArrays(array $a, array $b): void /** * @param array{a: 'foo', b: 'bar', c?: 'baz'} $a - * @param array{17: 'foo', 19: 'bar'}|array{foo: 17, bar: 19} $b - * @param array{0: 'A', 1?: 'B', 2?: 'C'} $c */ - public function constantArrays(array $a, array $b, array $c): void + public function constantArrays(array $a): void { + $b = rand(0, 1) ? [17 => 'foo', 19 => 'bar'] : ['foo' => 17, 'bar' => 19]; + $c = ['A', 'B', 'C']; + if (rand(0, 1)) { + unset($c[1]); + } + if (rand(0, 1)) { + unset($c[2]); + } assertType('array{}', array_reverse([])); assertType('array{}', array_reverse([], true)); diff --git a/tests/PHPStan/Analyser/nsrt/array-search.php b/tests/PHPStan/Analyser/nsrt/array-search.php index 680c56844af..8fb0fda7d96 100644 --- a/tests/PHPStan/Analyser/nsrt/array-search.php +++ b/tests/PHPStan/Analyser/nsrt/array-search.php @@ -51,7 +51,7 @@ public function constantArrays(array $arr, string $string): void /** @var array{1, '1', '2'} $arr */ assertType('1', array_search('1', $arr, true)); - assertType('0|1', array_search('1', $arr)); + assertType('0', array_search('1', $arr)); assertType('1|2|false', array_search($string, $arr, true)); assertType('0|1|2|false', array_search($string, $arr, false)); } diff --git a/tests/PHPStan/Analyser/nsrt/array-shape-key-order-php81.php b/tests/PHPStan/Analyser/nsrt/array-shape-key-order-php81.php new file mode 100644 index 00000000000..07eb100b2f9 --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/array-shape-key-order-php81.php @@ -0,0 +1,21 @@ += 8.1 + +declare(strict_types = 1); + +namespace ArrayShapeKeyOrderPhp81; + +use function PHPStan\Testing\assertType; + +/** + * @param array{x: 'p', y: 'q'} $k + * @param list{1, 2} $l + * @param array{foo: int, bar: string} $a + */ +function functionsWalkingShapeWithKeysInAnyOrder(array $k, array $l, array $a): void +{ + // pairs come in the order the array has its keys + assertType("non-empty-array<'p'|'q', 1|2>", array_combine($k, $l)); + + // the spread array does not know the order of its keys either + assertType("0|'bar'|'foo'", array_key_first([...$a, 'c'])); +} diff --git a/tests/PHPStan/Analyser/nsrt/array-shape-key-order.php b/tests/PHPStan/Analyser/nsrt/array-shape-key-order.php new file mode 100644 index 00000000000..743fc4b07ed --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/array-shape-key-order.php @@ -0,0 +1,288 @@ + 2, 'a' => 1]; + assertType('bool', $p === $x); +} + +/** + * @param array{a: int, b: int} $p + * @param array{a: int, c: int} $q + * @param array{a: int, b?: int} $r + */ +function phpDocShapesWithDifferentKeys(array $p, array $q, array $r): void +{ + assertType('false', $p === $q); + assertType('false', $q === $p); + assertType('bool', $p === $r); + assertType('false', $p == $q); +} + +/** + * @param array{a: int, b: 1} $s + * @param array{a: int, b: 2} $t + */ +function phpDocShapesWithDifferentValues(array $s, array $t): void +{ + assertType('false', $s == $t); +} + +/** + * @param array{a: int, b: string} $p + */ +function firstAndLast(array $p): void +{ + // the first and last key of a PHPDoc shape can be any of its keys + assertType("'a'|'b'", array_key_first($p)); + assertType("'a'|'b'", array_key_last($p)); + assertType('int|string', reset($p)); + assertType('int|string', end($p)); + assertType('int|string', array_first($p)); + assertType('int|string', array_last($p)); + assertType('int|string', array_pop($p)); + + $x = ['a' => 1, 'b' => 'x']; + assertType("'a'", array_key_first($x)); + assertType("'b'", array_key_last($x)); + assertType('1', reset($x)); + assertType("'x'", end($x)); + assertType('1', array_first($x)); + assertType("'x'", array_last($x)); + assertType('1', array_shift($x)); + + $y = rand(0, 1) ? ['a' => 1, 'b' => 'x'] : ['c' => true]; + assertType("'a'|'c'", array_key_first($y)); + assertType("'b'|'c'", array_key_last($y)); +} + +function literalArrays(): void +{ + $x = ['a' => 1, 'b' => 2]; + $y = ['b' => 2, 'a' => 1]; + assertType('false', $x === $y); + assertType('true', $x === ['a' => 1, 'b' => 2]); +} + +/** + * @param array{a: int, b: int} $p + */ +function searchFindsFirstMatchingKey(array $p, bool $b): void +{ + // array_search() returns the first key whose value matches + assertType("'a'", array_search(1, ['a' => 1, 'b' => 1])); + assertType("'b'", array_search(1, ['a' => 2, 'b' => 1, 'c' => 1], true)); + assertType("'b'", array_search('1', ['a' => 2, 'b' => 1, 'c' => '1'])); + assertType("'c'", array_search('1', ['a' => 2, 'b' => 1, 'c' => '1'], true)); + + // a key that might be missing does not hide the keys after it + $x = ['a' => 1, 'b' => 1]; + if ($b) { + unset($x['a']); + } + assertType("'a'|'b'", array_search(1, $x)); + + // a PHPDoc shape does not say which of its keys comes first + $p['a'] = 1; + $p['b'] = 1; + assertType("'a'|'b'", array_search(1, $p)); +} + +/** + * @param list $segments + * @param array $call + */ +function literalShapeHoldsPhpDocShape(array &$segments, array $call): void +{ + $start = $call['start']; + $end = $start + $call['time']; + $segments[] = ['start' => $start, 'end' => $end]; + + // the literal shape holds the PHPDoc one once it forgets its key order + assertType('non-empty-list', $segments); +} + +/** + * @param array{foo: int, bar: string, baz?: float} $a + */ +function positionsOfShapeWithKeysInAnyOrder(array $a): void +{ + // any of the keys can come at any position + assertType("list{0: 'bar'|'baz'|'foo', 1: 'bar'|'baz'|'foo', 2?: 'bar'|'baz'|'foo'}", array_keys($a)); + assertType('list{0: float|int|string, 1: float|int|string, 2?: float|int|string}', array_values($a)); + assertType('array{foo?: int, bar?: string, baz?: float}', array_slice($a, 0, 1)); + assertType('array{baz?: float, bar: string, foo: int}', array_reverse($a)); + + $popped = $a; + array_pop($popped); + assertType('array{foo?: int, bar?: string, baz?: float}', $popped); + + $shifted = $a; + array_shift($shifted); + assertType('array{foo?: int, bar?: string, baz?: float}', $shifted); +} + +function positionsOfIntegerKeysInAnyOrder(bool $b): void +{ + $x = $b ? [1 => 'a', 0 => 'b'] : [0 => 'b', 1 => 'a']; + assertType("array{'a'|'b', 'a'|'b'}", array_values($x)); + assertType("array{'a'|'b'}", array_slice($x, 0, 1)); + assertType("array{'a'|'b', 'a'|'b'}", array_reverse($x)); + assertType("array{'b', 'a'}", array_reverse($x, true)); + + $shifted = $x; + array_shift($shifted); + assertType("array{'a'|'b'}", $shifted); +} + +/** + * @param array{a: int, b: string} $s + * @param array{0: int, a: string} $m + * @param array{1: int, 0: string} $i + */ +function positionsOfKeysInAnyOrderMaybePreserved(array $s, array $m, array $i, bool $b): void +{ + // the keys may be renumbered by positions that are not known + assertType('array{array{int|string}, array{int|string}}', array_chunk($s, 1, $b)); + assertType('array{int|string, int|string}', array_reverse($i, $b)); + assertType('array{int|string}', array_slice($i, 0, 1, $b)); + + // the string key keeps its name, the integer key is renumbered by a position that is not known + assertType("non-empty-array<0|'a', int|string>", array_reverse($m)); + assertType("non-empty-array<0|'a', int|string>", array_reverse($m, $b)); + assertType("array<0|'a', int|string>", array_slice($m, 0, 1)); + assertType("array<0|'a', int|string>", array_slice($m, 0, 1, $b)); +} + +/** + * @param array{x: array{id: 'a', v: 1}, y: array{id: 'b', v: 2}} $rows + * @param array{x?: array{v: 1}, y: array{v: 2}} $optionalRows + * @param array{x: array{id: 'a', v: 1}, y: array{v: 2}, z: array{v: 3}} $stringIndexed + * @param array{x: array{id: 5, v: 1}, y: array{v: 2}} $integerIndexed + * @param array{x: array{id: int|string, v: 1}, y: array{v: 2}} $maybeIntegerIndexed + * @param array{a: array{v: 1}, b: array{v: 3}, ...} $unsealedRows + * @param array{x: array{id: 'a', v: 1}, y: array{v: 2}, ...} $stringIndexedExtras + * @param array{x: array{id: 'a', v: 1}, y: array{v: 2}, ...} $integerIndexedExtras + * @param array{x: array{id: 'a', v: 1}, y: array{v: 2}, ...} $maybeIntegerIndexedExtras + */ +function columnsOfRowsInAnyOrder( + array $rows, + array $optionalRows, + array $stringIndexed, + array $integerIndexed, + array $maybeIntegerIndexed, + array $unsealedRows, + array $stringIndexedExtras, + array $integerIndexedExtras, + array $maybeIntegerIndexedExtras, +): void +{ + // the rows without the index are numbered by their positions, which are not known + assertType('array{1|2, 1|2}', array_column($rows, 'v', 'nope')); + assertType('0', array_key_first(array_column($rows, 'v', 'nope'))); + assertType('list{0: 1|2, 1?: 1|2}', array_column($optionalRows, 'v')); + assertType('array{a: 1, 0: 2|3, 1: 2|3}', array_column($stringIndexed, 'v', 'id')); + assertType('array{1|2|3, 1|2|3, ...<2>}', array_column($unsealedRows, 'v')); + assertType('array{1|2|3, 1|2|3, ...<3>}', array_column($stringIndexedExtras, 'v', 'nope')); + assertType("array{a: 1, 0: 2, ...<'b', 3>}", array_column($stringIndexedExtras, 'v', 'id')); + + // the numbers continue after the integer keys of the rows that come before them + assertType('non-empty-array', array_column($integerIndexed, 'v', 'id')); + assertType('non-empty-array', array_column($maybeIntegerIndexed, 'v', 'id')); + assertType("non-empty-array<'a'|int, 1|2|3>", array_column($integerIndexedExtras, 'v', 'id')); + assertType('non-empty-array', array_column($maybeIntegerIndexedExtras, 'v', 'id')); + + // the same rows in a literal array know their positions + assertType('array{1, 2}', array_column(['x' => ['id' => 'a', 'v' => 1], 'y' => ['id' => 'b', 'v' => 2]], 'v', 'nope')); + assertType('array{5: 1, 6: 2}', array_column(['x' => ['id' => 5, 'v' => 1], 'y' => ['v' => 2]], 'v', 'id')); +} + +/** + * @param array{x: 'p', y: 'q'} $k + * @param list{1, 2} $l + * @param array{foo: int, bar: string} $a + */ +function functionsWalkingShapeWithKeysInAnyOrder(array $k, array $l, array $a, bool $b): void +{ + $u = $b ? [1 => 'a', 0 => 'b'] : [0 => 'b', 1 => 'a']; + + // pairs, values and renumbered keys come in the order the array has its keys + assertType("'p,p'|'p,q'|'q,p'|'q,q'", implode(',', $k)); + assertType("'a,a'|'a,b'|'b,a'|'b,b'", implode(',', $u)); + assertType("array{1: 'p'|'q', 2: 'p'|'q'}", array_combine($l, $k)); + assertType("array{'a'|'b', 'a'|'b', 'c'}", array_merge($u, ['c'])); + assertType("array{'a'|'b', 'a'|'b', 'c'}", [...$u, 'c']); + assertType("array{array{'a'|'b'}, array{'a'|'b'}}", array_chunk($u, 1)); + + // the merged arrays do not know the order of their keys either + assertType("'bar'|'foo'|'z'", array_key_first(array_merge($a, ['z' => true]))); +} + +/** + * @param list{0: int, 1: string, 2: float} $l + */ +function listKnowsItsKeyOrder(array $l, bool $b): void +{ + assertType('array{1: string}', array_slice($l, 1, 1, true)); + + $u = $b ? ['a' => 0, 17 => 1, 'b' => 2] : [17 => 1, 'a' => 0, 'b' => 2]; + assertType('array{array{0|1|2}, array{0|1|2}, array{0|1|2}}', array_chunk($u, 1)); +} + +/** + * @param array{a: array{id: 1}, b: array{id: 2}} $rows + * @param array{a: int, b: string} $ab + */ +function functionsBuildingArraysFromShapeWithKeysInAnyOrder(array $rows, array $ab): void +{ + // the new array has its keys in the order of a shape that does not know it + assertType('array{1|2, 1|2}', array_column($rows, 'id')); + assertType('1|2', array_key_first(array_column($rows, 'id', 'id'))); + assertType("'a'|'b'", array_key_first(array_filter($ab, static fn ($v): bool => true))); + assertType("'a'|'b'|'c'", array_key_first(array_replace($ab, ['c' => 1]))); + + // the same functions over literal arrays know the order + assertType('array{1, 2}', array_column(['a' => ['id' => 1], 'b' => ['id' => 2]], 'id')); + assertType('1', array_key_first(array_column(['a' => ['id' => 1], 'b' => ['id' => 2]], 'id', 'id'))); + assertType("'a'", array_key_first(array_filter(['a' => 1, 'b' => 'x'], static fn ($v): bool => true))); + assertType("'a'", array_key_first(array_replace(['a' => 1, 'b' => 2], ['c' => 1]))); + assertType("'rows'", array_key_first(compact('rows', 'ab'))); +} + +/** + * @param list $flags + */ +function loopWideningKeyOrder(array $flags, string $s): void +{ + // the same keys in the same order in every pass keep it + $data = []; + foreach ($flags as $i => $flag) { + $data[] = ['int', 'string|null', $s . $i]; + } + foreach ($data as $row) { + assertType('true', array_is_list($row)); + assertType('0', array_key_first($row)); + } + + // a pass can add the keys in another order than the previous one did + $x = ['bundle' => 'b']; + foreach ($flags as $flag) { + if ($flag) { + $x['css'] = 1; + } else { + $x['js'] = 2; + } + } + assertType("'bundle'|'css'|'js'", array_key_last($x)); +} diff --git a/tests/PHPStan/Analyser/nsrt/array-shape-list-optional.php b/tests/PHPStan/Analyser/nsrt/array-shape-list-optional.php index 9acad79f69b..9d1300754bc 100644 --- a/tests/PHPStan/Analyser/nsrt/array-shape-list-optional.php +++ b/tests/PHPStan/Analyser/nsrt/array-shape-list-optional.php @@ -28,8 +28,8 @@ public function doFoo( // The trailing keys can never appear in a list (4 sits past the gap at // 3; foo is not an integer), so they are dropped, leaving the valid // list projection rather than an empty *NEVER*. - assertType('array{0: string, 1: int, 2?: string}', $invalid1); - assertType('array{0: string, 1: int, 2?: string}', $invalid2); + assertType('list{0: string, 1: int, 2?: string}', $invalid1); + assertType('list{0: string, 1: int, 2?: string}', $invalid2); } } diff --git a/tests/PHPStan/Analyser/nsrt/array-shift.php b/tests/PHPStan/Analyser/nsrt/array-shift.php index 12bbd0a1bab..0f1d548686c 100644 --- a/tests/PHPStan/Analyser/nsrt/array-shift.php +++ b/tests/PHPStan/Analyser/nsrt/array-shift.php @@ -31,30 +31,48 @@ public function compoundTypes(array $arr): void public function constantArrays(array $arr): void { - /** @var array{a: 0, b: 1, c: 2} $arr */ - assertType('0|1|2', array_shift($arr)); + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + assertType('0', array_shift($arr)); assertType('array{b: 1, c: 2}', $arr); - /** @var array{} $arr */ + $arr = []; assertType('null', array_shift($arr)); assertType('array{}', $arr); } public function constantArraysWithOptionalKeys(array $arr): void { - /** @var array{a?: 0, b: 1, c: 2} $arr */ - assertType('0|1|2', array_shift($arr)); + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['a']); + } + assertType('0|1', array_shift($arr)); assertType('array{b?: 1, c: 2}', $arr); - /** @var array{a: 0, b?: 1, c: 2} $arr */ - assertType('0|1|2', array_shift($arr)); + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['b']); + } + assertType('0', array_shift($arr)); assertType('array{b?: 1, c: 2}', $arr); - /** @var array{a: 0, b: 1, c?: 2} $arr */ - assertType('0|1|2', array_shift($arr)); + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['c']); + } + assertType('0', array_shift($arr)); assertType('array{b: 1, c?: 2}', $arr); - /** @var array{a?: 0, b?: 1, c?: 2} $arr */ + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['a']); + } + if (rand(0, 1)) { + unset($arr['b']); + } + if (rand(0, 1)) { + unset($arr['c']); + } assertType('0|1|2|null', array_shift($arr)); assertType('array{b?: 1, c?: 2}', $arr); } diff --git a/tests/PHPStan/Analyser/nsrt/array-slice.php b/tests/PHPStan/Analyser/nsrt/array-slice.php index 553ac9bd1fb..55a3ec0068d 100644 --- a/tests/PHPStan/Analyser/nsrt/array-slice.php +++ b/tests/PHPStan/Analyser/nsrt/array-slice.php @@ -56,27 +56,30 @@ public function normalArrays(array $arr): void public function constantArrays(array $arr): void { - /** @var array{17: 'foo', b: 'bar', 19: 'baz'} $arr */ + $arr = [17 => 'foo', 'b' => 'bar', 19 => 'baz']; assertType('array{b: \'bar\', 0: \'baz\'}', array_slice($arr, 1, 2)); assertType('array{b: \'bar\', 19: \'baz\'}', array_slice($arr, 1, 2, true)); assertType('array<17|19|\'b\', \'bar\'|\'baz\'|\'foo\'>', array_slice($arr, rand(0, 1) ? 0 : 1, rand(0, 1) ? 0 : 1)); - /** @var array{17: 'foo', 19: 'bar', 21: 'baz'}|array{foo: 17, bar: 19, baz: 21} $arr */ + $arr = rand(0, 1) ? [17 => 'foo', 19 => 'bar', 21 => 'baz'] : ['foo' => 17, 'bar' => 19, 'baz' => 21]; assertType('array{\'bar\', \'baz\'}|array{bar: 19, baz: 21}', array_slice($arr, 1, 2)); assertType('array{19: \'bar\', 21: \'baz\'}|array{bar: 19, baz: 21}', array_slice($arr, 1, 2, true)); - /** @var array{17: 'foo', b: 'bar', 19: 'baz'} $arr */ + $arr = [17 => 'foo', 'b' => 'bar', 19 => 'baz']; assertType('array{}', array_slice($arr, -1, -1)); assertType('array{}', array_slice($arr, -1, -1, true)); - /** @var array{17: 'foo', b: 'bar', 19: 'baz'} $arr */ + $arr = [17 => 'foo', 'b' => 'bar', 19 => 'baz']; assertType('array{}', array_slice($arr, -1, -2)); assertType('array{}', array_slice($arr, -1, -2, true)); } public function constantArraysWithOptionalKeys(array $arr): void { - /** @var array{a?: 0, b: 1, c: 2} $arr */ + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['a']); + } assertType('array{a?: 0, b?: 1}', array_slice($arr, 0, 1)); assertType('array{a?: 0, b: 1, c: 2}', array_slice($arr, 0)); assertType('array{a?: 0, b: 1, c: 2}', array_slice($arr, -99)); @@ -87,20 +90,38 @@ public function constantArraysWithOptionalKeys(array $arr): void assertType('array{}', array_slice($arr, -99, -99)); assertType('array{}', array_slice($arr, 99)); - /** @var array{a?: 0, b?: 1, c: 2, d: 3, e: 4} $arr */ + $arr = ['a' => 0, 'b' => 1, 'c' => 2, 'd' => 3, 'e' => 4]; + if (rand(0, 1)) { + unset($arr['a']); + } + if (rand(0, 1)) { + unset($arr['b']); + } assertType('array{c?: 2, d?: 3, e?: 4}', array_slice($arr, 2, 1)); assertType('array{b?: 1, c?: 2, d: 3, e?: 4}', array_slice($arr, 1, 3)); assertType('array{e: 4}', array_slice($arr, -1)); assertType('array{d: 3}', array_slice($arr, -2, 1)); - /** @var array{a: 0, b: 1, c: 2, d?: 3, e?: 4} $arr */ + $arr = ['a' => 0, 'b' => 1, 'c' => 2, 'd' => 3, 'e' => 4]; + if (rand(0, 1)) { + unset($arr['d']); + } + if (rand(0, 1)) { + unset($arr['e']); + } assertType('array{c: 2}', array_slice($arr, 2, 1)); assertType('array{c?: 2, d?: 3, e?: 4}', array_slice($arr, -1)); assertType('array{b?: 1, c?: 2, d?: 3}', array_slice($arr, -2, 1)); assertType('array{a: 0, b: 1, c?: 2, d?: 3}', array_slice($arr, 0, -1)); assertType('array{a: 0, b?: 1, c?: 2}', array_slice($arr, 0, -2)); - /** @var array{a: 0, b?: 1, c: 2, d?: 3, e: 4} $arr */ + $arr = ['a' => 0, 'b' => 1, 'c' => 2, 'd' => 3, 'e' => 4]; + if (rand(0, 1)) { + unset($arr['b']); + } + if (rand(0, 1)) { + unset($arr['d']); + } assertType('array{b?: 1, c: 2, d?: 3, e?: 4}', array_slice($arr, 1, 2)); assertType('array{a: 0, b?: 1, c?: 2}', array_slice($arr, 0, 2)); assertType('array{a: 0}', array_slice($arr, 0, 1)); @@ -109,7 +130,10 @@ public function constantArraysWithOptionalKeys(array $arr): void assertType('array{a: 0, b?: 1, c: 2, d?: 3}', array_slice($arr, 0, -1)); assertType('array{c?: 2, d?: 3, e: 4}', array_slice($arr, -2)); - /** @var array{a: 0, b?: 1, c: 2} $arr */ + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['b']); + } assertType('array{a: 0, b?: 1}', array_slice($arr, 0, -1)); assertType('array{a: 0}', array_slice($arr, -3, 1)); } diff --git a/tests/PHPStan/Analyser/nsrt/array_first_last.php b/tests/PHPStan/Analyser/nsrt/array_first_last.php index cf3ba4857ec..726635b470a 100644 --- a/tests/PHPStan/Analyser/nsrt/array_first_last.php +++ b/tests/PHPStan/Analyser/nsrt/array_first_last.php @@ -11,13 +11,13 @@ */ function doFoo(array $stringArray, array $nonEmptyArray, $mixed, $arrayShape): void { - assertType("'a'|'b'|'c'", array_first([1 => 'a', 0 => 'b', 2 => 'c'])); + assertType("'a'", array_first([1 => 'a', 0 => 'b', 2 => 'c'])); assertType("'bar'|'foo'", array_first($arrayShape)); assertType('string|null', array_first($stringArray)); assertType('string', array_first($nonEmptyArray)); assertType('mixed', array_first($mixed)); - assertType("'a'|'b'|'c'", array_last([1 => 'a', 0 => 'b', 2 => 'c'])); + assertType("'c'", array_last([1 => 'a', 0 => 'b', 2 => 'c'])); assertType("'bar'|'foo'", array_last($arrayShape)); assertType('string|null', array_last($stringArray)); assertType('string', array_last($nonEmptyArray)); diff --git a/tests/PHPStan/Analyser/nsrt/array_splice.php b/tests/PHPStan/Analyser/nsrt/array_splice.php index dcbfe583feb..ed64cc74849 100644 --- a/tests/PHPStan/Analyser/nsrt/array_splice.php +++ b/tests/PHPStan/Analyser/nsrt/array_splice.php @@ -77,112 +77,98 @@ function insertViaArraySplice(array $arr): void function constantArrays(array $arr, array $arr2): void { - /** @var array{17: 'foo', b: 'bar', 19: 'baz'} $arr */ - $arr; + $arr = [17 => 'foo', 'b' => 'bar', 19 => 'baz']; $extract = array_splice($arr, 0, 1, ['hello']); assertType('array{0: \'hello\', b: \'bar\', 1: \'baz\'}', $arr); assertType('array{\'foo\'}', $extract); - /** @var array{17: 'foo', b: 'bar', 19: 'baz'} $arr */ - $arr; + $arr = [17 => 'foo', 'b' => 'bar', 19 => 'baz']; $extract = array_splice($arr, 1, 2, ['hello']); assertType('array{\'foo\', \'hello\'}', $arr); assertType('array{b: \'bar\', 0: \'baz\'}', $extract); - /** @var array{17: 'foo', b: 'bar', 19: 'baz'} $arr */ - $arr; + $arr = [17 => 'foo', 'b' => 'bar', 19 => 'baz']; $extract = array_splice($arr, 0, -1, ['hello']); assertType('array{\'hello\', \'baz\'}', $arr); assertType('array{0: \'foo\', b: \'bar\'}', $extract); - /** @var array{17: 'foo', b: 'bar', 19: 'baz'} $arr */ - $arr; + $arr = [17 => 'foo', 'b' => 'bar', 19 => 'baz']; $extract = array_splice($arr, 0, -2, ['hello']); assertType('array{0: \'hello\', b: \'bar\', 1: \'baz\'}', $arr); assertType('array{\'foo\'}', $extract); - /** @var array{17: 'foo', b: 'bar', 19: 'baz'} $arr */ - $arr; + $arr = [17 => 'foo', 'b' => 'bar', 19 => 'baz']; $extract = array_splice($arr, -1, -1, ['hello']); assertType('array{0: \'foo\', b: \'bar\', 1: \'hello\', 2: \'baz\'}', $arr); assertType('array{}', $extract); - /** @var array{17: 'foo', b: 'bar', 19: 'baz'} $arr */ - $arr; + $arr = [17 => 'foo', 'b' => 'bar', 19 => 'baz']; $extract = array_splice($arr, -2, -2, ['hello']); assertType('array{0: \'foo\', 1: \'hello\', b: \'bar\', 2: \'baz\'}', $arr); assertType('array{}', $extract); - /** @var array{17: 'foo', b: 'bar', 19: 'baz'} $arr */ - $arr; + $arr = [17 => 'foo', 'b' => 'bar', 19 => 'baz']; $extract = array_splice($arr, 99, 0, ['hello']); assertType('array{0: \'foo\', b: \'bar\', 1: \'baz\'}', $arr); assertType('array{}', $extract); - /** @var array{17: 'foo', b: 'bar', 19: 'baz'} $arr */ - $arr; + $arr = [17 => 'foo', 'b' => 'bar', 19 => 'baz']; $extract = array_splice($arr, 1, 99, ['hello']); assertType('array{\'foo\', \'hello\'}', $arr); assertType('array{b: \'bar\', 0: \'baz\'}', $extract); - /** @var array{17: 'foo', b: 'bar', 19: 'baz'} $arr */ - $arr; + $arr = [17 => 'foo', 'b' => 'bar', 19 => 'baz']; $extract = array_splice($arr, -99, 99, ['hello']); assertType('array{\'hello\'}', $arr); assertType('array{0: \'foo\', b: \'bar\', 1: \'baz\'}', $extract); - /** @var array{17: 'foo', b: 'bar', 19: 'baz'} $arr */ - $arr; + $arr = [17 => 'foo', 'b' => 'bar', 19 => 'baz']; $extract = array_splice($arr, 0, -99, ['hello']); assertType('array{0: \'hello\', 1: \'foo\', b: \'bar\', 2: \'baz\'}', $arr); assertType('array{}', $extract); - /** @var array{17: 'foo', b: 'bar', 19: 'baz'} $arr */ - $arr; + $arr = [17 => 'foo', 'b' => 'bar', 19 => 'baz']; $extract = array_splice($arr, -2, 1, ['hello']); assertType('array{\'foo\', \'hello\', \'baz\'}', $arr); assertType('array{b: \'bar\'}', $extract); - /** @var array{17: 'foo', b: 'bar', 19: 'baz'} $arr */ - $arr; + $arr = [17 => 'foo', 'b' => 'bar', 19 => 'baz']; $extract = array_splice($arr, -1, 1, ['hello']); assertType('array{0: \'foo\', b: \'bar\', 1: \'hello\'}', $arr); assertType('array{\'baz\'}', $extract); - /** @var array{17: 'foo', b: 'bar', 19: 'baz'} $arr */ - $arr; + $arr = [17 => 'foo', 'b' => 'bar', 19 => 'baz']; $extract = array_splice($arr, 0, null, ['hello']); assertType('array{\'hello\'}', $arr); assertType('array{0: \'foo\', b: \'bar\', 1: \'baz\'}', $extract); - /** @var array{17: 'foo', b: 'bar', 19: 'baz'} $arr */ - $arr; + $arr = [17 => 'foo', 'b' => 'bar', 19 => 'baz']; $extract = array_splice($arr, 0); assertType('array{}', $arr); assertType('array{0: \'foo\', b: \'bar\', 1: \'baz\'}', $extract); - /** @var array{17: 'foo', b: 'bar', 19: 'baz'} $arr */ + $arr = [17 => 'foo', 'b' => 'bar', 19 => 'baz']; /** @var array<\stdClass> $arr2 */ $arr; $extract = array_splice($arr, 1, 1, $arr2); assertType('non-empty-array, \'baz\'|\'foo\'|stdClass>', $arr); assertType('array{b: \'bar\'}', $extract); - /** @var array{17: 'foo', b: 'bar', 19: 'baz'} $arr */ + $arr = [17 => 'foo', 'b' => 'bar', 19 => 'baz']; /** @var array<\stdClass> $arr2 */ $arr; $extract = array_splice($arr, 0, 1, $arr2); assertType('non-empty-array<\'b\'|int<0, max>, \'bar\'|\'baz\'|stdClass>', $arr); assertType('array{\'foo\'}', $extract); - /** @var array{17: 'foo', b: 'bar', 19: 'baz'} $arr */ + $arr = [17 => 'foo', 'b' => 'bar', 19 => 'baz']; /** @var array{x: 'x', y?: 'y', 3: 66}|array{z: 'z', 5?: 77, 4: int} $arr2 */ $arr; $extract = array_splice($arr, 0, 1, $arr2); - assertType('array{0: \'x\', 1: 66|\'y\', 2: 66|\'baz\', b: \'bar\', 3?: \'baz\'}|array{0: \'z\', 1: int, 2: \'baz\'|int, b: \'bar\', 3?: \'baz\'}', $arr); + assertType('array{0: \'z\'|int, 1: \'z\'|int, 2: \'baz\'|\'z\'|int, b: \'bar\', 3?: \'baz\'}|array{0: 66|\'x\'|\'y\', 1: 66|\'x\'|\'y\', 2: 66|\'baz\'|\'x\'|\'y\', b: \'bar\', 3?: \'baz\'}', $arr); assertType('array{\'foo\'}', $extract); - /** @var array{17: 'foo', b: 'bar', 19: 'baz'} $arr */ + $arr = [17 => 'foo', 'b' => 'bar', 19 => 'baz']; /** @var array{x: 'x', y?: 'y', 3: 66}|array{z: 'z', 5?: 77, 4: int}|array $arr2 */ $arr; $extract = array_splice($arr, 0, 1, $arr2); @@ -192,128 +178,134 @@ function constantArrays(array $arr, array $arr2): void function constantArraysWithOptionalKeys(array $arr): void { - /** - * @see https://3v4l.org/2UJ3u - * @var array{a?: 0, b: 1, c: 2} $arr - */ - $arr; + // @see https://3v4l.org/2UJ3u + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['a']); + } $extract = array_splice($arr, 0, 1, ['hello']); assertType('array{0: \'hello\', b?: 1, c: 2}', $arr); assertType('array{a?: 0, b?: 1}', $extract); - /** - * @see https://3v4l.org/Aq4l6 - * @var array{a?: 0, b: 1, c: 2} $arr - */ - $arr; + // @see https://3v4l.org/Aq4l6 + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['a']); + } $extract = array_splice($arr, 1, 1, ['hello']); assertType('array{a?: 0, b?: 1, 0: \'hello\', c?: 2}', $arr); assertType('array{b?: 1, c?: 2}', $extract); - /** - * @see https://3v4l.org/GBMps - * @var array{a?: 0, b: 1, c: 2} $arr - */ - $arr; + // @see https://3v4l.org/GBMps + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['a']); + } $extract = array_splice($arr, -1, 0, ['hello']); assertType('array{a?: 0, b: 1, 0: \'hello\', c: 2}', $arr); assertType('array{}', $extract); - /** - * @see https://3v4l.org/dQVgY - * @var array{a?: 0, b: 1, c: 2} $arr - */ - $arr; + // @see https://3v4l.org/dQVgY + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['a']); + } $extract = array_splice($arr, 0, -1, ['hello']); assertType('array{0: \'hello\', c: 2}', $arr); assertType('array{a?: 0, b: 1}', $extract); - /** - * @see https://3v4l.org/5XWRC - * @var array{a: 0, b?: 1, c: 2} $arr - */ - $arr; + // @see https://3v4l.org/5XWRC + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['b']); + } $extract = array_splice($arr, 0, 1, ['hello']); assertType('array{0: \'hello\', b?: 1, c: 2}', $arr); assertType('array{a: 0}', $extract); - /** - * @see https://3v4l.org/QXZre - * @var array{a: 0, b?: 1, c: 2} $arr - */ - $arr; + // @see https://3v4l.org/QXZre + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['b']); + } $extract = array_splice($arr, 1, 1, ['hello']); assertType('array{a: 0, 0: \'hello\', c?: 2}', $arr); assertType('array{b?: 1, c?: 2}', $extract); - /** - * @see https://3v4l.org/4JvMu - * @var array{a: 0, b?: 1, c: 2} $arr - */ - $arr; + // @see https://3v4l.org/4JvMu + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['b']); + } $extract = array_splice($arr, -1, 0, ['hello']); assertType('array{a: 0, b?: 1, 0: \'hello\', c: 2}', $arr); assertType('array{}', $extract); - /** - * @see https://3v4l.org/srHon - * @var array{a: 0, b?: 1, c: 2} $arr - */ - $arr; + // @see https://3v4l.org/srHon + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['b']); + } $extract = array_splice($arr, 0, -1, ['hello']); assertType('array{0: \'hello\', c: 2}', $arr); assertType('array{a: 0, b?: 1}', $extract); - /** - * @see https://3v4l.org/d0b0c - * @var array{a: 0, b: 1, c?: 2} $arr - */ - $arr; + // @see https://3v4l.org/d0b0c + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['c']); + } $extract = array_splice($arr, 0, 1, ['hello']); assertType('array{0: \'hello\', b: 1, c?: 2}', $arr); assertType('array{a: 0}', $extract); - /** - * @see https://3v4l.org/OPfIf - * @var array{a: 0, b: 1, c?: 2} $arr - */ - $arr; + // @see https://3v4l.org/OPfIf + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['c']); + } $extract = array_splice($arr, 1, 1, ['hello']); assertType('array{a: 0, 0: \'hello\', c?: 2}', $arr); assertType('array{b: 1}', $extract); - /** - * @see https://3v4l.org/b9R9E - * @var array{a: 0, b: 1, c?: 2} $arr - */ - $arr; + // @see https://3v4l.org/b9R9E + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['c']); + } $extract = array_splice($arr, -1, 0, ['hello']); assertType('array{a: 0, b: 1, 0: \'hello\', c?: 2}', $arr); assertType('array{}', $extract); - /** - * @see https://3v4l.org/0lFX6 - * @var array{a: 0, b: 1, c?: 2} $arr - */ - $arr; + // @see https://3v4l.org/0lFX6 + $arr = ['a' => 0, 'b' => 1, 'c' => 2]; + if (rand(0, 1)) { + unset($arr['c']); + } $extract = array_splice($arr, 0, -1, ['hello']); assertType('array{0: \'hello\', b?: 1, c?: 2}', $arr); assertType('array{a: 0, b?: 1}', $extract); - /** - * @see https://3v4l.org/PLHYv - * @var array{a: 0, b?: 1, c?: 2, d: 3} $arr - */ - $arr; + // @see https://3v4l.org/PLHYv + $arr = ['a' => 0, 'b' => 1, 'c' => 2, 'd' => 3]; + if (rand(0, 1)) { + unset($arr['b']); + } + if (rand(0, 1)) { + unset($arr['c']); + } $extract = array_splice($arr, 1, 2, ['hello']); assertType('array{a: 0, 0: \'hello\', d?: 3}', $arr); assertType('array{b?: 1, c?: 2, d?: 3}', $extract); - /** - * @see https://3v4l.org/Li5bj - * @var array{a: 0, b?: 1, c?: 2, d: 3} $arr - */ - $arr; + // @see https://3v4l.org/Li5bj + $arr = ['a' => 0, 'b' => 1, 'c' => 2, 'd' => 3]; + if (rand(0, 1)) { + unset($arr['b']); + } + if (rand(0, 1)) { + unset($arr['c']); + } $extract = array_splice($arr, -2, 2, ['hello']); assertType('array{a?: 0, b?: 1, 0: \'hello\'}', $arr); assertType('array{a?: 0, b?: 1, c?: 2, d: 3}', $extract); diff --git a/tests/PHPStan/Analyser/nsrt/array_values.php b/tests/PHPStan/Analyser/nsrt/array_values.php index e9c5c8b4ae4..b747352a6f0 100644 --- a/tests/PHPStan/Analyser/nsrt/array_values.php +++ b/tests/PHPStan/Analyser/nsrt/array_values.php @@ -38,11 +38,18 @@ public function constantArrayType(): void assertType("list{0?: 'a'|'b'|'c', 1?: 'b'|'c', 2?: 'c'}", array_values($numbers)); } - /** - * @param array{a: 1, b?: 2, c: 3, d?: 4, e?: 5, f: 6} $shape - */ - public function optionalKeysBetweenRequiredKeys(array $shape): void + public function optionalKeysBetweenRequiredKeys(): void { + $shape = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6]; + if (rand(0, 1)) { + unset($shape['b']); + } + if (rand(0, 1)) { + unset($shape['d']); + } + if (rand(0, 1)) { + unset($shape['e']); + } assertType('list{0: 1, 1: 2|3, 2: 3|4|5|6, 3?: 4|5|6, 4?: 5|6, 5?: 6}', array_values($shape)); } diff --git a/tests/PHPStan/Analyser/nsrt/binary.php b/tests/PHPStan/Analyser/nsrt/binary.php index d1d7f29ffac..0574f90407b 100644 --- a/tests/PHPStan/Analyser/nsrt/binary.php +++ b/tests/PHPStan/Analyser/nsrt/binary.php @@ -561,7 +561,7 @@ public function doFoo(array $generalArray) assertType('bool', array_key_exists('foo', $generalArray)); assertType('string', sprintf($string, $string, 1)); assertType('\'foo bar\'', sprintf('%s %s', 'foo', 'bar')); - assertType('array{}|array{\'password\'}|array{0: \'username\', 1?: \'password\'}', $coalesceArray); + assertType('array{}|array{\'password\'}|list{0: \'username\', 1?: \'password\'}', $coalesceArray); assertType('array{1, 2, 3}', $arrayToBeUnset); assertType('array{1, 2, 3}', $arrayToBeUnset2); assertType('array{0?: 1, 1?: 2, 2?: 3}', $arrayToBeUnset3); diff --git a/tests/PHPStan/Analyser/nsrt/bug-11580.php b/tests/PHPStan/Analyser/nsrt/bug-11580.php index 2e4f8200dbd..edaea2d026d 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-11580.php +++ b/tests/PHPStan/Analyser/nsrt/bug-11580.php @@ -10,7 +10,7 @@ public function bad(string $in): void { $matches = []; if (preg_match('~^/xxx/([\w\-]+)/?([\w\-]+)?/?$~', $in, $matches)) { - assertType('array{0: non-falsy-string, 1: non-empty-string, 2?: non-empty-string}', $matches); + assertType('list{0: non-falsy-string, 1: non-empty-string, 2?: non-empty-string}', $matches); } } @@ -19,16 +19,16 @@ public function bad2(string $in): void $matches = []; $result = preg_match('~^/xxx/([\w\-]+)/?([\w\-]+)?/?$~', $in, $matches); if ($result) { - assertType('array{0: non-falsy-string, 1: non-empty-string, 2?: non-empty-string}', $matches); + assertType('list{0: non-falsy-string, 1: non-empty-string, 2?: non-empty-string}', $matches); } } public function bad3(string $in): void { $result = preg_match('~^/xxx/([\w\-]+)/?([\w\-]+)?/?$~', $in, $matches); - assertType('array{}|array{0: non-falsy-string, 1: non-empty-string, 2?: non-empty-string}', $matches); + assertType('array{}|list{0: non-falsy-string, 1: non-empty-string, 2?: non-empty-string}', $matches); if ($result) { - assertType('array{0: non-falsy-string, 1: non-empty-string, 2?: non-empty-string}', $matches); + assertType('list{0: non-falsy-string, 1: non-empty-string, 2?: non-empty-string}', $matches); } } diff --git a/tests/PHPStan/Analyser/nsrt/bug-11600.php b/tests/PHPStan/Analyser/nsrt/bug-11600.php new file mode 100644 index 00000000000..47e73c8f04e --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/bug-11600.php @@ -0,0 +1,64 @@ + 1, 'bar' => 2]; +$b = ['bar' => 2, 'foo' => 1]; + +HelloWorld::sayHello($a); +HelloWorld::sayHello($b); + +class ExplicitIntegerKeys +{ + + /** + * @param array{1, 2} $implicit + * @param array{0: 1, 1: 2} $explicit + * @param array{1: 2, 0: 1} $explicitBackwards + * @param array{0: 1, 2: 2} $explicitWithGap + */ + public static function shapes(array $implicit, array $explicit, array $explicitBackwards, array $explicitWithGap): void + { + // the keys of `array{1, 2}` are 0 and 1 in this order: it is a list + assertType('true', array_is_list($implicit)); + assertType('1', array_values($implicit)[0]); + assertType('0', array_key_first($implicit)); + + // `array{0: 1, 1: 2}` only says the keys 0 and 1 are present, in any order + assertType('bool', array_is_list($explicit)); + assertType('1|2', array_values($explicit)[0]); + assertType('0|1', array_key_first($explicit)); + + assertType('bool', array_is_list($explicitBackwards)); + assertType('1|2', array_values($explicitBackwards)[0]); + + // no order of the keys 0 and 2 is a list + assertType('false', array_is_list($explicitWithGap)); + } + + /** + * @param list{1: 2, 0: 1} $list + * @param array{1: 2, 0: 1}&list $intersection + */ + public static function lists(array $list, array $intersection): void + { + // a list has its keys in ascending order + assertType('array{1, 2}', $list); + assertType('0', array_key_first($list)); + assertType('array{1, 2}', $intersection); + assertType('1', array_values($intersection)[0]); + } + +} diff --git a/tests/PHPStan/Analyser/nsrt/bug-11858.php b/tests/PHPStan/Analyser/nsrt/bug-11858.php index bcd0136d964..83416383b35 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-11858.php +++ b/tests/PHPStan/Analyser/nsrt/bug-11858.php @@ -19,11 +19,11 @@ public function sayBar(): void $arr[] = 'C'; } - assertType("array{}|array{'C'}|array{0: 'B', 1?: 'C'}|list{0: 'A', 1?: 'B'|'C', 2?: 'C'}", $arr); + assertType("array{}|array{'C'}|list{0: 'A', 1?: 'B'|'C', 2?: 'C'}|list{0: 'B', 1?: 'C'}", $arr); if (count($arr) >= 2 && $arr[0] === 'A') { if (array_key_exists(1, $arr) && $arr[1] === 'C') { - assertType("array{0: 'A', 1: 'C', 2?: 'C'}", $arr); + assertType("list{0: 'A', 1: 'C', 2?: 'C'}", $arr); } } } diff --git a/tests/PHPStan/Analyser/nsrt/bug-1283.php b/tests/PHPStan/Analyser/nsrt/bug-1283.php index 058c739bb97..558cb7137d6 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-1283.php +++ b/tests/PHPStan/Analyser/nsrt/bug-1283.php @@ -21,7 +21,7 @@ function (array $levels): void { throw new \UnexpectedValueException(sprintf('Unsupported level `%s`', $level)); } - assertType('array{0: 1, 1?: 3}', $allowedElements); + assertType('list{0: 1, 1?: 3}', $allowedElements); assertVariableCertainty(TrinaryLogic::createYes(), $allowedElements); } }; diff --git a/tests/PHPStan/Analyser/nsrt/bug-13655.php b/tests/PHPStan/Analyser/nsrt/bug-13655.php index dd1ff17588b..6a296a19ff6 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-13655.php +++ b/tests/PHPStan/Analyser/nsrt/bug-13655.php @@ -32,7 +32,7 @@ public function generateStructure(): void } } // a write to a key addEntryForId() may not have added creates an entry without the other key - assertType('non-empty-array', $structure); + assertType('non-empty-array', $structure); } /** diff --git a/tests/PHPStan/Analyser/nsrt/bug-14081.php b/tests/PHPStan/Analyser/nsrt/bug-14081.php index ea7acd51cfc..b31b4617fc9 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-14081.php +++ b/tests/PHPStan/Analyser/nsrt/bug-14081.php @@ -10,8 +10,9 @@ function first(array $array): mixed { if (($key = array_key_first($array))) { - assertType('int<1, max>', $key); - assertType('non-empty-list', $array); + // the first key of a list is 0, which is falsy + assertType('*NEVER*', $key); + assertType('*NEVER*', $array); assertType('string', $array[$key]); return $array[$key]; } @@ -39,15 +40,15 @@ function maybeNonEmpty(): void } assertType("array{}|array{'one', 'two'}", $array); $key = array_key_last($array); - assertType('0|1|null', $key); - assertType("'one'|'two'", $array[$key]); + assertType('1|null', $key); + assertType("'two'", $array[$key]); } /** @param list $array */ function firstNotNull(array $array): mixed { if (($key = array_key_first($array)) !== null) { - assertType('int<0, max>', $key); + assertType('0', $key); assertType('non-empty-list', $array); assertType('string', $array[$key]); return $array[$key]; @@ -71,7 +72,7 @@ function lastNotNull(array $array): mixed function noIf(array $array): void { $key = array_key_first($array); - assertType('int<0, max>|null', $key); + assertType('0|null', $key); assertType('list', $array); assertType('string', $array[$key]); @@ -79,7 +80,7 @@ function noIf(array $array): void return; } $key = array_key_first($array); - assertType('int<0, max>', $key); - assertType('non-empty-list', $array); + assertType('0', $key); + assertType('non-empty-list&hasOffsetValue(0, string)', $array); assertType('string', $array[$key]); } diff --git a/tests/PHPStan/Analyser/nsrt/bug-14177.php b/tests/PHPStan/Analyser/nsrt/bug-14177.php index 26ef94e5577..2f92a75a34c 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-14177.php +++ b/tests/PHPStan/Analyser/nsrt/bug-14177.php @@ -14,7 +14,7 @@ public function testList(array $b): void if (array_key_exists(3, $b)) { assertType('array{string, string, string, string}', $b); } else { - assertType('array{0: string, 1: string, 2?: string}', $b); + assertType('list{0: string, 1: string, 2?: string}', $b); } assertType('list{0: string, 1: string, 2?: string, 3?: string}', $b); } diff --git a/tests/PHPStan/Analyser/nsrt/bug-14245.php b/tests/PHPStan/Analyser/nsrt/bug-14245.php index 63333b5de2e..ba167db13dc 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-14245.php +++ b/tests/PHPStan/Analyser/nsrt/bug-14245.php @@ -86,7 +86,7 @@ function overwriteKeyFirst(): void { if ($count > 0) { assertType('non-empty-list', $list); $list[array_key_first($list)] = 37; - assertType('non-empty-list', $list); + assertType('non-empty-list&hasOffsetValue(0, 37)', $list); } assertType('list', $list); @@ -97,7 +97,7 @@ function overwriteKeyFirstMaybeEmptyArray(): void { assertType('list', $list); // empty list might return NULL for array_key_first() $list[array_key_first($list)] = 37; - assertType('non-empty-list', $list); + assertType('non-empty-list&hasOffsetValue(0, 37)', $list); } function keyDifferentArray(array $arr): void { diff --git a/tests/PHPStan/Analyser/nsrt/bug-14297.php b/tests/PHPStan/Analyser/nsrt/bug-14297.php index 1c10d6f365a..9428fce0936 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-14297.php +++ b/tests/PHPStan/Analyser/nsrt/bug-14297.php @@ -15,7 +15,7 @@ function (): void { return; } - assertType("array{0: 'a'|'b', 1?: 'b'}", $a); + assertType("list{0: 'a'|'b', 1?: 'b'}", $a); assertType("int<1, 2>", count($a)); if (count($a) === 2) { diff --git a/tests/PHPStan/Analyser/nsrt/bug-14605.php b/tests/PHPStan/Analyser/nsrt/bug-14605.php index f12c7b1080c..fb3d32d5790 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-14605.php +++ b/tests/PHPStan/Analyser/nsrt/bug-14605.php @@ -6,7 +6,7 @@ function testPregMatchOptionalGroupWithCountAndSubstr(string $resource): void { if (preg_match("!^3(/.*)?$!", $resource, $m)) { - assertType('array{0: non-falsy-string, 1?: non-falsy-string}', $m); + assertType('list{0: non-falsy-string, 1?: non-falsy-string}', $m); $resource = count($m) > 1 ? substr($m[1], 1) : ''; assertType('string', $resource); } diff --git a/tests/PHPStan/Analyser/nsrt/bug-14651.php b/tests/PHPStan/Analyser/nsrt/bug-14651.php index 55e4c4ce931..174d9d26d99 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-14651.php +++ b/tests/PHPStan/Analyser/nsrt/bug-14651.php @@ -30,7 +30,7 @@ function inIf(string $s): void assertType('non-falsy-string', $s); assertType('array{string, string}', explode("\n", $s, 2)); assertType('array{string, string, ...}', explode("\n", $s)); - assertType('array{0: string, 1: string, 2?: string}', explode("\n", $s, 3)); + assertType('list{0: string, 1: string, 2?: string}', explode("\n", $s, 3)); } else { assertType('string', $s); } diff --git a/tests/PHPStan/Analyser/nsrt/bug-14708.php b/tests/PHPStan/Analyser/nsrt/bug-14708.php index d6a659fe14c..0bcceaef93d 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-14708.php +++ b/tests/PHPStan/Analyser/nsrt/bug-14708.php @@ -86,7 +86,7 @@ function testIntegerOnlyUnion(bool $flag): void { $result = [ ...($flag ? [1, 2, 3] : [4, 5]), ]; - assertType('array{0: 1|4, 1: 2|5, 2?: 3}', $result); + assertType('list{0: 1|4, 1: 2|5, 2?: 3}', $result); } function testEmptyVsNonEmpty(bool $flag): void { diff --git a/tests/PHPStan/Analyser/nsrt/bug-14820.php b/tests/PHPStan/Analyser/nsrt/bug-14820.php index 68436e9d868..491938fca99 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-14820.php +++ b/tests/PHPStan/Analyser/nsrt/bug-14820.php @@ -28,12 +28,12 @@ function doFoo(string $s): void // optional over a (sub) group of literals if (preg_match('~(a(bc)?d)~', $s, $m)) { - assertType("array{0: non-falsy-string, 1: 'abcd'|'ad', 2?: 'bc'}", $m); + assertType("list{0: non-falsy-string, 1: 'abcd'|'ad', 2?: 'bc'}", $m); } // optional over an alternation if (preg_match('~(a(b|c)?d)~', $s, $m)) { - assertType("array{0: non-falsy-string, 1: 'abd'|'acd'|'ad', 2?: 'b'|'c'}", $m); + assertType("list{0: non-falsy-string, 1: 'abd'|'acd'|'ad', 2?: 'b'|'c'}", $m); } // the classic colour/color example diff --git a/tests/PHPStan/Analyser/nsrt/bug-14938.php b/tests/PHPStan/Analyser/nsrt/bug-14938.php index dcca644a206..cfdeafea442 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-14938.php +++ b/tests/PHPStan/Analyser/nsrt/bug-14938.php @@ -70,7 +70,7 @@ public function mergedShapes(): void if (rand(0, 1)) { $b[1] = 'w'; } - assertType("array{0: 'z', 1?: 'w'}", $b); + assertType("list{0: 'z', 1?: 'w'}", $b); assertType('true', array_is_list($b)); // Shapes disjoint except for the empty array still admit the empty list. diff --git a/tests/PHPStan/Analyser/nsrt/bug-14940.php b/tests/PHPStan/Analyser/nsrt/bug-14940.php new file mode 100644 index 00000000000..1da5f9fcd23 --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/bug-14940.php @@ -0,0 +1,22 @@ + 2, 'foo' => 1]) === ['qux', 'foo'] -> $keys[1] === 'foo' is TRUE +f(['qux' => 2, 'foo' => 1]); + diff --git a/tests/PHPStan/Analyser/nsrt/bug-15247.php b/tests/PHPStan/Analyser/nsrt/bug-15247.php index 52dbcef3c81..97b8692e29d 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-15247.php +++ b/tests/PHPStan/Analyser/nsrt/bug-15247.php @@ -83,7 +83,7 @@ function optionalKeySpread(array $list, int $x): void $x = 5; // the reference is at offset 1 or 2, so no offset is narrowed - assertType('array{0: int, 1: int, 2?: int}', $a); + assertType('list{0: int, 1: int, 2?: int}', $a); } function unionSpreadWithDifferentSizes(bool $b, int $x): void @@ -91,7 +91,7 @@ function unionSpreadWithDifferentSizes(bool $b, int $x): void $list = $b ? [1, 2] : [1, 2, 3]; $a = [...$list, &$x]; $x = 5; - assertType('array{0: 1|5, 1: 2|5, 2: int, 3?: int}', $a); + assertType('list{0: 1|5, 1: 2|5, 2: int, 3?: int}', $a); } function unionSpreadWithSameSize(bool $b, int $x): void diff --git a/tests/PHPStan/Analyser/nsrt/bug-15679.php b/tests/PHPStan/Analyser/nsrt/bug-15679.php new file mode 100644 index 00000000000..53b33183275 --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/bug-15679.php @@ -0,0 +1,41 @@ + 0, 0 => 0] : [0 => 1, 1 => 0]; + assertType('array{0|1, 0}', $x); + assertType('bool', array_is_list($x)); + + $y = $b ? [1 => 'a', 0 => 'b'] : [0 => 'c', 1 => 'a']; + assertType('bool', array_is_list($y)); +} + +function g(bool $b): void +{ + $same = $b ? [1 => 'a', 0 => 'b'] : [0 => 'b', 1 => 'a']; + assertType('bool', array_is_list($same)); + + $y = $b ? [1 => 'a', 0 => 'b'] : [0 => 'c', 1 => 'a']; + if (!array_is_list($y)) { + assertType("array{'b'|'c', 'a'}", $y); + } + + if ($b) { + $z = [1 => 'a', 0 => 'b']; + } else { + $z = [0 => 'c', 1 => 'a']; + } + assertType('bool', array_is_list($z)); + + $s = $b ? ['x' => 1, 'y' => 2] : ['y' => 2, 'x' => 3]; + assertType('array{y: 2, x: 1|3}', $s); + assertType('bool', $s === ['x' => 1, 'y' => 2]); + + $ok = $b ? [1 => 'a', 0 => 'b'] : [0 => 'c', 1 => 'd']; + assertType("array{'c', 'd'}|array{1: 'a', 0: 'b'}", $ok); + assertType('bool', array_is_list($ok)); +} diff --git a/tests/PHPStan/Analyser/nsrt/bug-15820.php b/tests/PHPStan/Analyser/nsrt/bug-15820.php index 03c2abf27f0..a76d0dd15c6 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-15820.php +++ b/tests/PHPStan/Analyser/nsrt/bug-15820.php @@ -15,7 +15,7 @@ final class Recommender public function eventName(string $category): ?string { $definition = self::CATEGORIES[$category]; - assertType("array{0: 'reasonKey', 1: 'tokens', 2?: 'eventName'}", array_keys($definition)); + assertType("list{0: 'reasonKey', 1: 'eventName'|'tokens', 2?: 'tokens'}", array_keys($definition)); if (isset($definition['eventName'])) { assertType("'quote-request'", $definition['eventName']); return $definition['eventName']; diff --git a/tests/PHPStan/Analyser/nsrt/bug-15907.php b/tests/PHPStan/Analyser/nsrt/bug-15907.php index c69e7cc5562..e6872fc1c50 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-15907.php +++ b/tests/PHPStan/Analyser/nsrt/bug-15907.php @@ -20,7 +20,7 @@ function read(array $entries): array $result[$tag]['js'] = $file; } } - assertType("array, js?: string}|array{bundle: 'b', js: string, css?: non-empty-list}>", $result); + assertType("array, js?: string}|array{bundle: 'b', css?: non-empty-list, js: string}>", $result); return $result; } diff --git a/tests/PHPStan/Analyser/nsrt/bug-3789.php b/tests/PHPStan/Analyser/nsrt/bug-3789.php index 95934512e33..4fdaea016d9 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-3789.php +++ b/tests/PHPStan/Analyser/nsrt/bug-3789.php @@ -16,8 +16,8 @@ function doFoo(string $needle, array $haystack): void { $haystack[1] = 'foo'; assertType('0|1|2|false', array_search($needle, $haystack, true)); - assertType('0|1|2', array_search('foo', $haystack, true)); + assertType('0|1', array_search('foo', $haystack, true)); assertType('0|1|2|false', array_search($needle, $haystack)); - assertType('0|1|2', array_search('foo', $haystack)); + assertType('0|1', array_search('foo', $haystack)); } diff --git a/tests/PHPStan/Analyser/nsrt/bug-6936-limit.php b/tests/PHPStan/Analyser/nsrt/bug-6936-limit.php index 097de24af52..65b06f51b5c 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-6936-limit.php +++ b/tests/PHPStan/Analyser/nsrt/bug-6936-limit.php @@ -36,16 +36,16 @@ public function testLimits():void $arr[] = 'g'; } - assertType("array{'e', 2|'f'|'g', 3|'g'}|array{'f', 2|'g', 3}|array{0: 'd', 1: 2|'e'|'f'|'g', 2: 3|'f'|'g', 3?: 'g'}|array{1|'g', 2, 3}|list{0: 'a', 1: 2|'b'|'c'|'d'|'e'|'f'|'g', 2: 3|'c'|'d'|'e'|'f'|'g', 3?: 'd'|'e'|'f'|'g', 4?: 'e'|'f'|'g', 5?: 'f'|'g', 6?: 'g'}|list{0: 'b', 1: 2|'c'|'d'|'e'|'f'|'g', 2: 3|'d'|'e'|'f'|'g', 3?: 'e'|'f'|'g', 4?: 'f'|'g', 5?: 'g'}|list{0: 'c', 1: 2|'d'|'e'|'f'|'g', 2: 3|'e'|'f'|'g', 3?: 'f'|'g', 4?: 'g'}", $arr + $arr2); + assertType("array{'e', 2|'f'|'g', 3|'g'}|array{'f', 2|'g', 3}|array{1|'g', 2, 3}|list{0: 'a', 1: 2|'b'|'c'|'d'|'e'|'f'|'g', 2: 3|'c'|'d'|'e'|'f'|'g', 3?: 'd'|'e'|'f'|'g', 4?: 'e'|'f'|'g', 5?: 'f'|'g', 6?: 'g'}|list{0: 'b', 1: 2|'c'|'d'|'e'|'f'|'g', 2: 3|'d'|'e'|'f'|'g', 3?: 'e'|'f'|'g', 4?: 'f'|'g', 5?: 'g'}|list{0: 'c', 1: 2|'d'|'e'|'f'|'g', 2: 3|'e'|'f'|'g', 3?: 'f'|'g', 4?: 'g'}|list{0: 'd', 1: 2|'e'|'f'|'g', 2: 3|'f'|'g', 3?: 'g'}", $arr + $arr2); if (rand(0,1)) { $arr[] = 'h'; } - assertType("array{'f', 2|'g'|'h', 3|'h'}|array{'g', 2|'h', 3}|array{0: 'e', 1: 2|'f'|'g'|'h', 2: 3|'g'|'h', 3?: 'h'}|array{1|'h', 2, 3}|list{0: 'a', 1: 2|'b'|'c'|'d'|'e'|'f'|'g'|'h', 2: 3|'c'|'d'|'e'|'f'|'g'|'h', 3?: 'd'|'e'|'f'|'g'|'h', 4?: 'e'|'f'|'g'|'h', 5?: 'f'|'g'|'h', 6?: 'g'|'h', 7?: 'h'}|list{0: 'b', 1: 2|'c'|'d'|'e'|'f'|'g'|'h', 2: 3|'d'|'e'|'f'|'g'|'h', 3?: 'e'|'f'|'g'|'h', 4?: 'f'|'g'|'h', 5?: 'g'|'h', 6?: 'h'}|list{0: 'c', 1: 2|'d'|'e'|'f'|'g'|'h', 2: 3|'e'|'f'|'g'|'h', 3?: 'f'|'g'|'h', 4?: 'g'|'h', 5?: 'h'}|list{0: 'd', 1: 2|'e'|'f'|'g'|'h', 2: 3|'f'|'g'|'h', 3?: 'g'|'h', 4?: 'h'}", $arr + $arr2); + assertType("array{'f', 2|'g'|'h', 3|'h'}|array{'g', 2|'h', 3}|array{1|'h', 2, 3}|list{0: 'a', 1: 2|'b'|'c'|'d'|'e'|'f'|'g'|'h', 2: 3|'c'|'d'|'e'|'f'|'g'|'h', 3?: 'd'|'e'|'f'|'g'|'h', 4?: 'e'|'f'|'g'|'h', 5?: 'f'|'g'|'h', 6?: 'g'|'h', 7?: 'h'}|list{0: 'b', 1: 2|'c'|'d'|'e'|'f'|'g'|'h', 2: 3|'d'|'e'|'f'|'g'|'h', 3?: 'e'|'f'|'g'|'h', 4?: 'f'|'g'|'h', 5?: 'g'|'h', 6?: 'h'}|list{0: 'c', 1: 2|'d'|'e'|'f'|'g'|'h', 2: 3|'e'|'f'|'g'|'h', 3?: 'f'|'g'|'h', 4?: 'g'|'h', 5?: 'h'}|list{0: 'd', 1: 2|'e'|'f'|'g'|'h', 2: 3|'f'|'g'|'h', 3?: 'g'|'h', 4?: 'h'}|list{0: 'e', 1: 2|'f'|'g'|'h', 2: 3|'g'|'h', 3?: 'h'}", $arr + $arr2); if (rand(0,1)) { $arr[] = 'i'; } - assertType("array{'g', 2|'h'|'i', 3|'i'}|array{'h', 2|'i', 3}|array{0: 'f', 1: 2|'g'|'h'|'i', 2: 3|'h'|'i', 3?: 'i'}|array{1|'i', 2, 3}|list{0: 'a', 1: 2|'b'|'c'|'d'|'e'|'f'|'g'|'h'|'i', 2: 3|'c'|'d'|'e'|'f'|'g'|'h'|'i', 3?: 'd'|'e'|'f'|'g'|'h'|'i', 4?: 'e'|'f'|'g'|'h'|'i', 5?: 'f'|'g'|'h'|'i', 6?: 'g'|'h'|'i', 7?: 'h'|'i', 8?: 'i'}|list{0: 'b', 1: 2|'c'|'d'|'e'|'f'|'g'|'h'|'i', 2: 3|'d'|'e'|'f'|'g'|'h'|'i', 3?: 'e'|'f'|'g'|'h'|'i', 4?: 'f'|'g'|'h'|'i', 5?: 'g'|'h'|'i', 6?: 'h'|'i', 7?: 'i'}|list{0: 'c', 1: 2|'d'|'e'|'f'|'g'|'h'|'i', 2: 3|'e'|'f'|'g'|'h'|'i', 3?: 'f'|'g'|'h'|'i', 4?: 'g'|'h'|'i', 5?: 'h'|'i', 6?: 'i'}|list{0: 'd', 1: 2|'e'|'f'|'g'|'h'|'i', 2: 3|'f'|'g'|'h'|'i', 3?: 'g'|'h'|'i', 4?: 'h'|'i', 5?: 'i'}|list{0: 'e', 1: 2|'f'|'g'|'h'|'i', 2: 3|'g'|'h'|'i', 3?: 'h'|'i', 4?: 'i'}", $arr + $arr2); + assertType("array{'g', 2|'h'|'i', 3|'i'}|array{'h', 2|'i', 3}|array{1|'i', 2, 3}|list{0: 'a', 1: 2|'b'|'c'|'d'|'e'|'f'|'g'|'h'|'i', 2: 3|'c'|'d'|'e'|'f'|'g'|'h'|'i', 3?: 'd'|'e'|'f'|'g'|'h'|'i', 4?: 'e'|'f'|'g'|'h'|'i', 5?: 'f'|'g'|'h'|'i', 6?: 'g'|'h'|'i', 7?: 'h'|'i', 8?: 'i'}|list{0: 'b', 1: 2|'c'|'d'|'e'|'f'|'g'|'h'|'i', 2: 3|'d'|'e'|'f'|'g'|'h'|'i', 3?: 'e'|'f'|'g'|'h'|'i', 4?: 'f'|'g'|'h'|'i', 5?: 'g'|'h'|'i', 6?: 'h'|'i', 7?: 'i'}|list{0: 'c', 1: 2|'d'|'e'|'f'|'g'|'h'|'i', 2: 3|'e'|'f'|'g'|'h'|'i', 3?: 'f'|'g'|'h'|'i', 4?: 'g'|'h'|'i', 5?: 'h'|'i', 6?: 'i'}|list{0: 'd', 1: 2|'e'|'f'|'g'|'h'|'i', 2: 3|'f'|'g'|'h'|'i', 3?: 'g'|'h'|'i', 4?: 'h'|'i', 5?: 'i'}|list{0: 'e', 1: 2|'f'|'g'|'h'|'i', 2: 3|'g'|'h'|'i', 3?: 'h'|'i', 4?: 'i'}|list{0: 'f', 1: 2|'g'|'h'|'i', 2: 3|'h'|'i', 3?: 'i'}", $arr + $arr2); } } diff --git a/tests/PHPStan/Analyser/nsrt/bug-8084.php b/tests/PHPStan/Analyser/nsrt/bug-8084.php index 5879176649c..e9db5265a22 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-8084.php +++ b/tests/PHPStan/Analyser/nsrt/bug-8084.php @@ -15,6 +15,6 @@ class Bug8084 public function run(array $arr): void { assertType('0|1', array_shift($arr) ?? throw new Exception()); - assertType('1|null', array_shift($arr)); + assertType('0|1|null', array_shift($arr)); } } diff --git a/tests/PHPStan/Analyser/nsrt/bug-8864.php b/tests/PHPStan/Analyser/nsrt/bug-8864.php index cee48930142..5379b2b642a 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-8864.php +++ b/tests/PHPStan/Analyser/nsrt/bug-8864.php @@ -16,7 +16,7 @@ function test(array $a): void } if (!in_array(2, $a, true)) { - assertType('array{0: 1, 1?: *NEVER*}', $a); + assertType('list{0: 1, 1?: *NEVER*}', $a); } } diff --git a/tests/PHPStan/Analyser/nsrt/bug-9004.php b/tests/PHPStan/Analyser/nsrt/bug-9004.php index 2bb2f70163d..6a75186f42a 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-9004.php +++ b/tests/PHPStan/Analyser/nsrt/bug-9004.php @@ -7,7 +7,7 @@ $test = []; foreach (['a', 'b', 'c'] as $letter) { if (rand(0, 1) == 0) { - assertType("array{}|array{hi: 'hello'}|array{hi: array{0: 42, 1?: 42}}", $test); + assertType("array{}|array{hi: 'hello'}|array{hi: list{0: 42, 1?: 42}}", $test); if (isset($test['hi']) && is_string($test['hi'])) { continue; } diff --git a/tests/PHPStan/Analyser/nsrt/bug-yield-oversized-self-rejection.php b/tests/PHPStan/Analyser/nsrt/bug-yield-oversized-self-rejection.php index c439e012389..96488c3a430 100644 --- a/tests/PHPStan/Analyser/nsrt/bug-yield-oversized-self-rejection.php +++ b/tests/PHPStan/Analyser/nsrt/bug-yield-oversized-self-rejection.php @@ -90,7 +90,7 @@ function build(string $eventClass): array ]; } - assertType("array{eventClass: string, changes: array{0: non-empty-array{old?: array{1, '2022-08-04', array{array{'08:00', '12:00'}}}, new?: array{1, '2022-08-04', array{array{'08:00', '12:00'}}}}, 1: non-empty-array{old?: array{1, '2022-08-05', array{array{'08:00', '12:00'}}}, new?: array{1, '2022-08-05', array{array{'08:00', '12:00'}}}}, 2?: non-empty-array{old?: array{1, '2022-08-06', array{array{'08:00', '12:00'}}}, new?: array{1, '2022-08-06', array{array{'08:00', '12:00'}}}}}|array{0: non-empty-array{old?: array{1, '2022-08-04', array{array{'08:00', '12:00'}}}, new?: array{1, '2022-08-04', array{array{'08:00', '12:00'}}}}, 1?: non-empty-array{old?: array{1, '2022-08-10', array{array{'08:00', '12:00'}}}, new?: array{1, '2022-08-10', array{array{'08:00', '12:00'}}}}}|array{non-empty-array{old?: array{0: 1, 1: '2022-08-04', 2: array{array{'16:00', '23:00'}}, matchedTimecheckIds: array{42}}, new?: array{0: 1, 1: '2022-08-04', 2: array{array{'16:00', '23:00'}}, matchedTimecheckIds: array{42}}}}|array{non-empty-array{old?: array{1, '2022-08-04', array{array{'00:00', '00:00'}}}, new?: array{1, '2022-08-04', array{array{'00:00', '00:00'}}}}}|array{non-empty-array{old?: array{1, '2022-08-04', array{array{'08:00', '12:00'}, array{'14:00', '18:00'}}}, new?: array{1, '2022-08-04', array{array{'08:00', '12:00'}, array{'14:00', '18:00'}}}}}|array{non-empty-array{old?: array{1, '2022-08-04', array{array{'08:00', '12:00'}}}, new?: array{1, '2022-08-04', array{array{'08:00', '12:00'}}}}, non-empty-array{old?: array{2, '2022-08-05', array{array{'08:00', '12:00'}}}, new?: array{2, '2022-08-05', array{array{'08:00', '12:00'}}}}, non-empty-array{old?: array{2, '2022-08-06', array{array{'08:00', '12:00'}}}, new?: array{2, '2022-08-06', array{array{'08:00', '12:00'}}}}, non-empty-array{old?: array{3, '2022-08-06', array{array{'08:00', '12:00'}}}, new?: array{3, '2022-08-06', array{array{'08:00', '12:00'}}}}, non-empty-array{old?: array{3, '2022-08-10', array{array{'08:00', '12:00'}}}, new?: array{3, '2022-08-10', array{array{'08:00', '12:00'}}}}}|array{non-empty-array{old?: array{1, '2022-08-04', array{array{'22:00', '04:00'}}}, new?: array{1, '2022-08-04', array{array{'22:00', '04:00'}}}}}, matchedTimechecks: array{}|array{42: array{1, '2022-08-05T00:05/2022-08-05T02:00'}}, invalidates: array{}|array{array{1, '2022-08-04'|'2022-08-04/2022-08-05'|'2022-08-04/2022-08-06'}}|array{array{1, '2022-08-04'}, array{1, '2022-08-10'}}|array{array{1, '2022-08-04'}, array{2, '2022-08-05/2022-08-06'}, array{3, '2022-08-06'}, array{3, '2022-08-10'}}, persistenceEnabled?: false}", $r); + assertType("array{eventClass: string, changes: array{non-empty-array{old?: array{0: 1, 1: '2022-08-04', 2: array{array{'16:00', '23:00'}}, matchedTimecheckIds: array{42}}, new?: array{0: 1, 1: '2022-08-04', 2: array{array{'16:00', '23:00'}}, matchedTimecheckIds: array{42}}}}|array{non-empty-array{old?: array{1, '2022-08-04', array{array{'00:00', '00:00'}}}, new?: array{1, '2022-08-04', array{array{'00:00', '00:00'}}}}}|array{non-empty-array{old?: array{1, '2022-08-04', array{array{'08:00', '12:00'}, array{'14:00', '18:00'}}}, new?: array{1, '2022-08-04', array{array{'08:00', '12:00'}, array{'14:00', '18:00'}}}}}|array{non-empty-array{old?: array{1, '2022-08-04', array{array{'08:00', '12:00'}}}, new?: array{1, '2022-08-04', array{array{'08:00', '12:00'}}}}, non-empty-array{old?: array{2, '2022-08-05', array{array{'08:00', '12:00'}}}, new?: array{2, '2022-08-05', array{array{'08:00', '12:00'}}}}, non-empty-array{old?: array{2, '2022-08-06', array{array{'08:00', '12:00'}}}, new?: array{2, '2022-08-06', array{array{'08:00', '12:00'}}}}, non-empty-array{old?: array{3, '2022-08-06', array{array{'08:00', '12:00'}}}, new?: array{3, '2022-08-06', array{array{'08:00', '12:00'}}}}, non-empty-array{old?: array{3, '2022-08-10', array{array{'08:00', '12:00'}}}, new?: array{3, '2022-08-10', array{array{'08:00', '12:00'}}}}}|array{non-empty-array{old?: array{1, '2022-08-04', array{array{'22:00', '04:00'}}}, new?: array{1, '2022-08-04', array{array{'22:00', '04:00'}}}}}|list{0: non-empty-array{old?: array{1, '2022-08-04', array{array{'08:00', '12:00'}}}, new?: array{1, '2022-08-04', array{array{'08:00', '12:00'}}}}, 1: non-empty-array{old?: array{1, '2022-08-05', array{array{'08:00', '12:00'}}}, new?: array{1, '2022-08-05', array{array{'08:00', '12:00'}}}}, 2?: non-empty-array{old?: array{1, '2022-08-06', array{array{'08:00', '12:00'}}}, new?: array{1, '2022-08-06', array{array{'08:00', '12:00'}}}}}|list{0: non-empty-array{old?: array{1, '2022-08-04', array{array{'08:00', '12:00'}}}, new?: array{1, '2022-08-04', array{array{'08:00', '12:00'}}}}, 1?: non-empty-array{old?: array{1, '2022-08-10', array{array{'08:00', '12:00'}}}, new?: array{1, '2022-08-10', array{array{'08:00', '12:00'}}}}}, matchedTimechecks: array{}|array{42: array{1, '2022-08-05T00:05/2022-08-05T02:00'}}, invalidates: array{}|array{array{1, '2022-08-04'|'2022-08-04/2022-08-05'|'2022-08-04/2022-08-06'}}|array{array{1, '2022-08-04'}, array{1, '2022-08-10'}}|array{array{1, '2022-08-04'}, array{2, '2022-08-05/2022-08-06'}, array{3, '2022-08-06'}, array{3, '2022-08-10'}}, persistenceEnabled?: false}", $r); return $r; } diff --git a/tests/PHPStan/Analyser/nsrt/bug11480.php b/tests/PHPStan/Analyser/nsrt/bug11480.php index 5dbf27cc162..a558864f572 100644 --- a/tests/PHPStan/Analyser/nsrt/bug11480.php +++ b/tests/PHPStan/Analyser/nsrt/bug11480.php @@ -17,25 +17,25 @@ public function arrayGreatherThan(): void } if (count($x) > 0) { - assertType("array{'xy'}|array{0: 'ab', 1?: 'xy'}", $x); + assertType("array{'xy'}|list{0: 'ab', 1?: 'xy'}", $x); } else { assertType("array{}", $x); } - assertType("array{}|array{'xy'}|array{0: 'ab', 1?: 'xy'}", $x); + assertType("array{}|array{'xy'}|list{0: 'ab', 1?: 'xy'}", $x); if (count($x) > 1) { assertType("array{'ab', 'xy'}", $x); } else { - assertType("array{}|array{'xy'}|array{0: 'ab', 1?: 'xy'}", $x); + assertType("array{}|array{'xy'}|list{0: 'ab', 1?: 'xy'}", $x); } - assertType("array{}|array{'xy'}|array{0: 'ab', 1?: 'xy'}", $x); + assertType("array{}|array{'xy'}|list{0: 'ab', 1?: 'xy'}", $x); if (count($x) >= 1) { - assertType("array{'xy'}|array{0: 'ab', 1?: 'xy'}", $x); + assertType("array{'xy'}|list{0: 'ab', 1?: 'xy'}", $x); } else { assertType("array{}", $x); } - assertType("array{}|array{'xy'}|array{0: 'ab', 1?: 'xy'}", $x); + assertType("array{}|array{'xy'}|list{0: 'ab', 1?: 'xy'}", $x); } public function arraySmallerThan(): void @@ -51,16 +51,16 @@ public function arraySmallerThan(): void if (count($x) < 1) { assertType("array{}", $x); } else { - assertType("array{'xy'}|array{0: 'ab', 1?: 'xy'}", $x); + assertType("array{'xy'}|list{0: 'ab', 1?: 'xy'}", $x); } - assertType("array{}|array{'xy'}|array{0: 'ab', 1?: 'xy'}", $x); + assertType("array{}|array{'xy'}|list{0: 'ab', 1?: 'xy'}", $x); if (count($x) <= 1) { - assertType("array{}|array{'xy'}|array{0: 'ab', 1?: 'xy'}", $x); + assertType("array{}|array{'xy'}|list{0: 'ab', 1?: 'xy'}", $x); } else { assertType("array{'ab', 'xy'}", $x); } - assertType("array{}|array{'xy'}|array{0: 'ab', 1?: 'xy'}", $x); + assertType("array{}|array{'xy'}|list{0: 'ab', 1?: 'xy'}", $x); } public function intUnionCount(): void @@ -80,13 +80,13 @@ public function intUnionCount(): void assertType('1|2', $count); - assertType("array{}|array{'xy'}|array{0: 'ab', 1?: 'xy'}", $x); + assertType("array{}|array{'xy'}|list{0: 'ab', 1?: 'xy'}", $x); if (count($x) >= $count) { - assertType("array{'xy'}|array{0: 'ab', 1?: 'xy'}", $x); + assertType("array{'xy'}|list{0: 'ab', 1?: 'xy'}", $x); } else { - assertType("array{}|array{'xy'}|array{0: 'ab', 1?: 'xy'}", $x); + assertType("array{}|array{'xy'}|list{0: 'ab', 1?: 'xy'}", $x); } - assertType("array{}|array{'xy'}|array{0: 'ab', 1?: 'xy'}", $x); + assertType("array{}|array{'xy'}|list{0: 'ab', 1?: 'xy'}", $x); } /** @@ -102,12 +102,12 @@ public function intRangeCount($count): void $x[] = 'xy'; } - assertType("array{}|array{'xy'}|array{0: 'ab', 1?: 'xy'}", $x); + assertType("array{}|array{'xy'}|list{0: 'ab', 1?: 'xy'}", $x); if (count($x) >= $count) { - assertType("array{'xy'}|array{0: 'ab', 1?: 'xy'}", $x); + assertType("array{'xy'}|list{0: 'ab', 1?: 'xy'}", $x); } else { - assertType("array{}|array{'xy'}|array{0: 'ab', 1?: 'xy'}", $x); + assertType("array{}|array{'xy'}|list{0: 'ab', 1?: 'xy'}", $x); } - assertType("array{}|array{'xy'}|array{0: 'ab', 1?: 'xy'}", $x); + assertType("array{}|array{'xy'}|list{0: 'ab', 1?: 'xy'}", $x); } } diff --git a/tests/PHPStan/Analyser/nsrt/by-ref-writeback-native-type.php b/tests/PHPStan/Analyser/nsrt/by-ref-writeback-native-type.php index 6ebab6d0b0d..f1e207d1a9a 100644 --- a/tests/PHPStan/Analyser/nsrt/by-ref-writeback-native-type.php +++ b/tests/PHPStan/Analyser/nsrt/by-ref-writeback-native-type.php @@ -11,8 +11,8 @@ function offsetCapture(string $s): void return; } - assertType("array{0: array{non-falsy-string, int<-1, max>}, 1: array{'a', int<-1, max>}, 2?: array{'b', int<-1, max>}}", $m); - assertNativeType("array{0: array{non-falsy-string, int<-1, max>}, 1: array{'a', int<-1, max>}, 2?: array{'b', int<-1, max>}}", $m); + assertType("list{0: array{non-falsy-string, int<-1, max>}, 1: array{'a', int<-1, max>}, 2?: array{'b', int<-1, max>}}", $m); + assertNativeType("list{0: array{non-falsy-string, int<-1, max>}, 1: array{'a', int<-1, max>}, 2?: array{'b', int<-1, max>}}", $m); } function noFlags(string $s): void @@ -21,8 +21,8 @@ function noFlags(string $s): void return; } - assertType("array{0: non-falsy-string, 1: 'a', 2?: 'b'}", $m); - assertNativeType("array{0: non-falsy-string, 1: 'a', 2?: 'b'}", $m); + assertType("list{0: non-falsy-string, 1: 'a', 2?: 'b'}", $m); + assertNativeType("list{0: non-falsy-string, 1: 'a', 2?: 'b'}", $m); } /** @param-out string $v */ diff --git a/tests/PHPStan/Analyser/nsrt/conditional-expr-narrowing-through-variable.php b/tests/PHPStan/Analyser/nsrt/conditional-expr-narrowing-through-variable.php index 60872a8b458..c8dff73ec8b 100644 --- a/tests/PHPStan/Analyser/nsrt/conditional-expr-narrowing-through-variable.php +++ b/tests/PHPStan/Analyser/nsrt/conditional-expr-narrowing-through-variable.php @@ -42,6 +42,6 @@ function pregMatchNarrowsByRefVariable(string $in): void // preg_match has impure points (it writes $matches by ref), but $matches // is a plain variable so the narrowing attached to it must still survive // through the stored `$result` guard. - assertType('array{0: non-falsy-string, 1: non-empty-string, 2?: non-empty-string}', $matches); + assertType('list{0: non-falsy-string, 1: non-empty-string, 2?: non-empty-string}', $matches); } } diff --git a/tests/PHPStan/Analyser/nsrt/constant-array-optional-set.php b/tests/PHPStan/Analyser/nsrt/constant-array-optional-set.php index 00eca9e7f7e..75ac3abb548 100644 --- a/tests/PHPStan/Analyser/nsrt/constant-array-optional-set.php +++ b/tests/PHPStan/Analyser/nsrt/constant-array-optional-set.php @@ -13,7 +13,7 @@ public function doFoo() if (rand(0, 1)) { $a[] = 2; } - assertType('array{0: 1, 1?: 2}', $a); + assertType('list{0: 1, 1?: 2}', $a); if (rand(0, 1)) { $a[] = 3; } @@ -34,7 +34,7 @@ public function doBar() if (rand(0, 1)) { $a[] = 2; } - assertType('array{0: 1, 1?: 2}', $a); + assertType('list{0: 1, 1?: 2}', $a); if (rand(0, 1)) { $a[3] = 3; } diff --git a/tests/PHPStan/Analyser/nsrt/count-recursive.php b/tests/PHPStan/Analyser/nsrt/count-recursive.php index de2db167c7a..07f2a0f46c0 100644 --- a/tests/PHPStan/Analyser/nsrt/count-recursive.php +++ b/tests/PHPStan/Analyser/nsrt/count-recursive.php @@ -163,7 +163,7 @@ public function countConstantArray(array $anotherArray): void { if (rand(0,1)) { $arr[] = 10; } - assertType('array{0: 1, 1: 2, 2: 3, 3: array, 4?: 10}', $arr); + assertType('list{0: 1, 1: 2, 2: 3, 3: array, 4?: 10}', $arr); assertType('int<4, 5>', count($arr)); assertType('int<4, 5>', count($arr, COUNT_NORMAL)); assertType('int<1, max>', count($arr, COUNT_RECURSIVE)); // could be int<4, max> diff --git a/tests/PHPStan/Analyser/nsrt/count-type.php b/tests/PHPStan/Analyser/nsrt/count-type.php index 8ebe0c445eb..cc0d6437f0c 100644 --- a/tests/PHPStan/Analyser/nsrt/count-type.php +++ b/tests/PHPStan/Analyser/nsrt/count-type.php @@ -97,6 +97,19 @@ public function constantArrayWhichCanBecomeList(string $h): void assertType('array{non-falsy-string, non-empty-string}', $matches); } + /** @param array{a: string, b: string, c?: string, d?: int} $arr */ + public function stringKeys(array $arr): void + { + if (count($arr) === 2) { + assertType('array{a: string, b: string}', $arr); + } elseif (count($arr) === 4) { + assertType('array{a: string, b: string, c: string, d: int}', $arr); + } else { + // either of the optional keys + assertType('array{a: string, b: string, c?: string, d?: int}', $arr); + } + } + } /** diff --git a/tests/PHPStan/Analyser/nsrt/equality-narrowing-new-world.php b/tests/PHPStan/Analyser/nsrt/equality-narrowing-new-world.php index 7fac601ee1e..1ed2bec8eff 100644 --- a/tests/PHPStan/Analyser/nsrt/equality-narrowing-new-world.php +++ b/tests/PHPStan/Analyser/nsrt/equality-narrowing-new-world.php @@ -166,7 +166,7 @@ public function countNarrowingShapes(array $list, array $shape, array $ints): vo assertType('array{string}', $list); } if (count($shape) === 1) { - assertType('array{a: int, b?: string}', $shape); + assertType('array{a: int}', $shape); } if (sizeof($ints) === 0) { assertType('array{}', $ints); @@ -334,7 +334,7 @@ public function generalExprVsExpr($five, $is, Suit $suit, Suit $otherSuit, $arrO public function typeBasedConstantSides(array $list, string $s, int $smallSize, int $zero, string $stringName, $m): void { if (count($list) === $smallSize) { - assertType('array{0: string, 1: string, 2?: string}', $list); + assertType('list{0: string, 1: string, 2?: string}', $list); } if (count($list) === $zero) { assertType('array{}', $list); @@ -518,7 +518,7 @@ public function funcCallAgainstNull(array $list): void assertType('non-empty-list', $list); } if (($key = array_key_first($list)) !== null) { - assertType('int<0, max>', $key); + assertType('0', $key); assertType('non-empty-list', $list); assertType('string', $list[$key]); } diff --git a/tests/PHPStan/Analyser/nsrt/explode.php b/tests/PHPStan/Analyser/nsrt/explode.php index 58e1c31ce0a..24247f3ecc4 100644 --- a/tests/PHPStan/Analyser/nsrt/explode.php +++ b/tests/PHPStan/Analyser/nsrt/explode.php @@ -57,7 +57,7 @@ function constantSplit(string $delimiterUnion, string $stringUnion, int $limitUn // below minus the number of parts all produce an empty array assertType("array{'a', 'b', 'c'}", explode(',', 'a,b,c', $largeLimitRange)); assertType("array{}|array{'a'}", explode(',', 'a,b,c', $negativeLimitRange)); - assertType("array{}|array{'a', 'b', 'c'}|array{'a,b,c'}|array{0: 'a', 1?: 'b'|'b,c'}", explode(',', 'a,b,c', $unknownLimit)); + assertType("array{}|array{'a', 'b', 'c'}|array{'a,b,c'}|list{0: 'a', 1?: 'b'|'b,c'}", explode(',', 'a,b,c', $unknownLimit)); // the empty separator throws a ValueError on PHP 8+, so only the ',' split remains assertType("array{'a', 'b'}", explode($maybeEmptyDelimiter, 'a,b')); diff --git a/tests/PHPStan/Analyser/nsrt/first-class-callable-replay.php b/tests/PHPStan/Analyser/nsrt/first-class-callable-replay.php index 18a28061987..e3fd00a9e56 100644 --- a/tests/PHPStan/Analyser/nsrt/first-class-callable-replay.php +++ b/tests/PHPStan/Analyser/nsrt/first-class-callable-replay.php @@ -36,7 +36,7 @@ function problems(\DateTimeImmutable $d, array $arr, string $s, mixed $x): void $pm = preg_match(...); $pm('/(a)(b)?/', 'ab', $mm); - assertType("array{}|array{0: non-falsy-string, 1: 'a', 2?: 'b'}", $mm); + assertType("array{}|list{0: non-falsy-string, 1: 'a', 2?: 'b'}", $mm); $ake = array_key_exists(...); if ($ake('a', $arr)) { diff --git a/tests/PHPStan/Analyser/nsrt/foreach-loop-variables.php b/tests/PHPStan/Analyser/nsrt/foreach-loop-variables.php index 199c21dfd19..362472165ca 100644 --- a/tests/PHPStan/Analyser/nsrt/foreach-loop-variables.php +++ b/tests/PHPStan/Analyser/nsrt/foreach-loop-variables.php @@ -87,7 +87,7 @@ public function doFoo(string $s) assertType('1|2|3', $nullableInt); - assertType('array{0: 1, 1: 1|2|3, 2?: 1|2|3}|array{1|2|3}|array{2, 1|2|3}', $integers); + assertType('array{1|2|3}|array{2, 1|2|3}|list{0: 1, 1: 1|2|3, 2?: 1|2|3}', $integers); assertType('non-empty-array', $this->property); @@ -108,7 +108,7 @@ public function doFoo(string $s) assertType('2|null', $emptyForeachKey); - assertType('array{}|array{0: 2, 1?: 3}|array{3}|list{0: 1, 1?: 2|3, 2?: 3}', $integers); + assertType('array{}|array{3}|list{0: 1, 1?: 2|3, 2?: 3}|list{0: 2, 1?: 3}', $integers); assertType('array', $this->property); diff --git a/tests/PHPStan/Analyser/nsrt/get-defined-vars.php b/tests/PHPStan/Analyser/nsrt/get-defined-vars.php index f61a316d886..a092d06be2c 100644 --- a/tests/PHPStan/Analyser/nsrt/get-defined-vars.php +++ b/tests/PHPStan/Analyser/nsrt/get-defined-vars.php @@ -11,14 +11,14 @@ function doFoo(int $param) { $local = "foo"; assertType('array{param: int, local: \'foo\'}', get_defined_vars()); - assertType('array{\'param\', \'local\'}', array_keys(get_defined_vars())); + assertType('array{\'local\'|\'param\', \'local\'|\'param\'}', array_keys(get_defined_vars())); } function doBar(int $param) { global $global; $local = "foo"; assertType('array{param: int, global: mixed, local: \'foo\'}', get_defined_vars()); - assertType('array{\'param\', \'global\', \'local\'}', array_keys(get_defined_vars())); + assertType('array{\'global\'|\'local\'|\'param\', \'global\'|\'local\'|\'param\', \'global\'|\'local\'|\'param\'}', array_keys(get_defined_vars())); } function doConditional(int $param) { diff --git a/tests/PHPStan/Analyser/nsrt/implode.php b/tests/PHPStan/Analyser/nsrt/implode.php index ecd36a0570f..4bc7269592a 100644 --- a/tests/PHPStan/Analyser/nsrt/implode.php +++ b/tests/PHPStan/Analyser/nsrt/implode.php @@ -34,28 +34,28 @@ public function constants() { assertType("'1,345'", join(',', [self::ONE, '345'])); } - /** @param array{0: 1|2, 1: 'a'|'b'} $constArr */ + /** @param array{1|2, 'a'|'b'} $constArr */ public function constArrays($constArr) { assertType("'1a'|'1b'|'2a'|'2b'", implode('', $constArr)); } - /** @param array{0: 1|2|3, 1: 'a'|'b'|'c'} $constArr */ + /** @param array{1|2|3, 'a'|'b'|'c'} $constArr */ public function constArrays2($constArr) { assertType("'1a'|'1b'|'1c'|'2a'|'2b'|'2c'|'3a'|'3b'|'3c'", implode('', $constArr)); } - /** @param array{0: 1, 1: 'a'|'b', 2: 'x'|'y'} $constArr */ + /** @param array{1, 'a'|'b', 'x'|'y'} $constArr */ public function constArrays3($constArr) { assertType("'1ax'|'1ay'|'1bx'|'1by'", implode('', $constArr)); } - /** @param array{0: 1, 1: 'a'|'b', 2?: 'x'|'y'} $constArr */ + /** @param list{0: 1, 1: 'a'|'b', 2?: 'x'|'y'} $constArr */ public function constArrays4($constArr) { assertType("'1a'|'1ax'|'1ay'|'1b'|'1bx'|'1by'", implode('', $constArr)); } - /** @param array{10: 1|2|3, xy: 'a'|'b'|'c'} $constArr */ - public function constArrays5($constArr) { + public function constArrays5() { + $constArr = [10 => rand(0, 1) ? 1 : (rand(0, 1) ? 2 : 3), 'xy' => rand(0, 1) ? 'a' : (rand(0, 1) ? 'b' : 'c')]; assertType("'1a'|'1b'|'1c'|'2a'|'2b'|'2c'|'3a'|'3b'|'3c'", implode('', $constArr)); } @@ -64,8 +64,8 @@ public function constArrays6($constArr) { assertType("lowercase-string&non-falsy-string", implode('', $constArr)); } - /** @param array{10: 1|2|bool, xy: 'a'|'b'|'c'} $constArr */ - public function constArrays7($constArr) { + public function constArrays7() { + $constArr = [10 => rand(0, 1) ? 1 : (rand(0, 1) ? 2 : (bool) rand(0, 1)), 'xy' => rand(0, 1) ? 'a' : (rand(0, 1) ? 'b' : 'c')]; assertType("'1a'|'1b'|'1c'|'2a'|'2b'|'2c'|'a'|'b'|'c'", implode('', $constArr)); } diff --git a/tests/PHPStan/Analyser/nsrt/integer-union-bounds.php b/tests/PHPStan/Analyser/nsrt/integer-union-bounds.php index d21775a6c8f..d08a7ad7ea9 100644 --- a/tests/PHPStan/Analyser/nsrt/integer-union-bounds.php +++ b/tests/PHPStan/Analyser/nsrt/integer-union-bounds.php @@ -26,7 +26,7 @@ function countGreaterThanOrEqualUnion(array $arr, int $u): void if ($u <= count($arr)) { assertType('list{0: 1, 1?: 2, 2?: 3, 3?: 4}', $arr); } else { - assertType('array{0: 1, 1?: 2}', $arr); + assertType('list{0: 1, 1?: 2}', $arr); } } @@ -57,7 +57,7 @@ function countGreaterThanList(array $list, int $u, int $r): void function countIdenticalUnion(array $list, int $u): void { if (count($list) === $u) { - assertType('array{0: int, 1: int, 2?: int}', $list); + assertType('list{0: int, 1: int, 2?: int}', $list); } } @@ -68,7 +68,7 @@ function countIdenticalUnion(array $list, int $u): void function countIdenticalRange(array $list, int $r): void { if (count($list) === $r) { - assertType('array{0: int, 1: int, 2?: int}', $list); + assertType('list{0: int, 1: int, 2?: int}', $list); } } diff --git a/tests/PHPStan/Analyser/nsrt/list-count.php b/tests/PHPStan/Analyser/nsrt/list-count.php index d9bd37e9b52..12cdf01a280 100644 --- a/tests/PHPStan/Analyser/nsrt/list-count.php +++ b/tests/PHPStan/Analyser/nsrt/list-count.php @@ -321,15 +321,15 @@ protected function testOptionalKeysInUnionArray($row): void } if (count($row) === 1) { - assertType('array{0: int, 3?: string|null}|array{string}', $row); + assertType('array{int}|array{string}', $row); } else { - assertType('array{0: int, 3?: string|null}', $row); + assertType('array{0: int, 3: string|null}', $row); } if (count($row) === 2) { - assertType('array{0: int, 3?: string|null}', $row); + assertType('array{0: int, 3: string|null}', $row); } else { - assertType('array{0: int, 3?: string|null}|array{string}', $row); + assertType('array{int}|array{string}', $row); } if (count($row) === 3) { @@ -354,7 +354,7 @@ protected function testOptionalKeysInUnionListWithIntRange($row, $listRow, $twoO if (count($row) >= $twoOrThree) { assertType('list{0: int, 1: string|null, 2?: int|null, 3?: float|null}', $row); } else { - assertType('array{0: int, 1?: string|null}|array{string}', $row); + assertType('array{string}|list{0: int, 1?: string|null}', $row); } if (count($row) >= $tenOrEleven) { @@ -372,11 +372,11 @@ protected function testOptionalKeysInUnionListWithIntRange($row, $listRow, $twoO if (count($row) >= $maxThree) { assertType('array{string}|list{0: int, 1?: string|null, 2?: int|null, 3?: float|null}', $row); } else { - assertType('array{0: int, 1?: string|null}|array{string}', $row); + assertType('array{string}|list{0: int, 1?: string|null}', $row); } if (count($row) >= $threeOrMoreInRangeLimit) { - assertType('array{0: int, 1: string|null, 2: int|null, 3?: float|null}', $row); + assertType('list{0: int, 1: string|null, 2: int|null, 3?: float|null}', $row); } else { assertType('array{string}|list{0: int, 1?: string|null, 2?: int|null, 3?: float|null}', $row); } @@ -388,7 +388,7 @@ protected function testOptionalKeysInUnionListWithIntRange($row, $listRow, $twoO } if (count($row) >= $threeOrMoreOverRangeLimit) { - assertType('array{0: int, 1: string|null, 2: int|null, 3?: float|null}', $row); + assertType('list{0: int, 1: string|null, 2: int|null, 3?: float|null}', $row); } else { assertType('array{string}|list{0: int, 1?: string|null, 2?: int|null, 3?: float|null}', $row); } diff --git a/tests/PHPStan/Analyser/nsrt/list-shapes.php b/tests/PHPStan/Analyser/nsrt/list-shapes.php index 8ea8b4c9cea..59680a27f85 100644 --- a/tests/PHPStan/Analyser/nsrt/list-shapes.php +++ b/tests/PHPStan/Analyser/nsrt/list-shapes.php @@ -20,7 +20,7 @@ public function bar($l1, $l2, $l3, $l4, $l5, $l6): void assertType("array{'a'}", $l2); assertType("array{'a'}", $l3); assertType("array{'a', 'b'}", $l4); - assertType("array{0: 'a', 1?: 'b'}", $l5); + assertType("list{0: 'a', 1?: 'b'}", $l5); assertType("array{'a', 'b', ...}", $l6); } } diff --git a/tests/PHPStan/Analyser/nsrt/minmax-arrays.php b/tests/PHPStan/Analyser/nsrt/minmax-arrays.php index bd94a81fb3c..98011fc6bca 100644 --- a/tests/PHPStan/Analyser/nsrt/minmax-arrays.php +++ b/tests/PHPStan/Analyser/nsrt/minmax-arrays.php @@ -101,7 +101,7 @@ function dummy3(array $ints): void function dummy4(\DateTimeInterface $dateA, ?\DateTimeInterface $dateB): void { - assertType('array{0: DateTimeInterface, 1?: DateTimeInterface}', array_filter([$dateA, $dateB])); + assertType('list{0: DateTimeInterface, 1?: DateTimeInterface}', array_filter([$dateA, $dateB])); assertType('DateTimeInterface', min(array_filter([$dateA, $dateB]))); assertType('DateTimeInterface', max(array_filter([$dateA, $dateB]))); assertType('array{0?: DateTimeInterface}', array_filter([$dateB])); diff --git a/tests/PHPStan/Analyser/nsrt/minmax-php8.php b/tests/PHPStan/Analyser/nsrt/minmax-php8.php index 2c75f363c96..9cca2e920aa 100644 --- a/tests/PHPStan/Analyser/nsrt/minmax-php8.php +++ b/tests/PHPStan/Analyser/nsrt/minmax-php8.php @@ -101,7 +101,7 @@ function dummy3(array $ints): void function dummy4(\DateTimeInterface $dateA, ?\DateTimeInterface $dateB): void { - assertType('array{0: DateTimeInterface, 1?: DateTimeInterface}', array_filter([$dateA, $dateB])); + assertType('list{0: DateTimeInterface, 1?: DateTimeInterface}', array_filter([$dateA, $dateB])); assertType('DateTimeInterface', min(array_filter([$dateA, $dateB]))); assertType('DateTimeInterface', max(array_filter([$dateA, $dateB]))); assertType('array{0?: DateTimeInterface}', array_filter([$dateB])); diff --git a/tests/PHPStan/Analyser/nsrt/minmax.php b/tests/PHPStan/Analyser/nsrt/minmax.php index 0295aa58177..1dd3b8fd75c 100644 --- a/tests/PHPStan/Analyser/nsrt/minmax.php +++ b/tests/PHPStan/Analyser/nsrt/minmax.php @@ -6,7 +6,7 @@ function dummy4(\DateTimeInterface $dateA, ?\DateTimeInterface $dateB): void { - assertType('array{0: DateTimeInterface, 1?: DateTimeInterface}', array_filter([$dateA, $dateB])); + assertType('list{0: DateTimeInterface, 1?: DateTimeInterface}', array_filter([$dateA, $dateB])); assertType('DateTimeInterface', min(array_filter([$dateA, $dateB]))); assertType('DateTimeInterface', max(array_filter([$dateA, $dateB]))); assertType('array{0?: DateTimeInterface}', array_filter([$dateB])); diff --git a/tests/PHPStan/Analyser/nsrt/narrow-tagged-union.php b/tests/PHPStan/Analyser/nsrt/narrow-tagged-union.php index 6095fb5932d..c736b3965a6 100644 --- a/tests/PHPStan/Analyser/nsrt/narrow-tagged-union.php +++ b/tests/PHPStan/Analyser/nsrt/narrow-tagged-union.php @@ -103,9 +103,9 @@ public function arrayIntRangeSize(): void if (count($x) === 1) { assertType("array{'ab'}|array{'xy'}", $x); } else { - assertType("array{}|array{0: 'ab', 1?: 'xy'}", $x); + assertType("array{}|list{0: 'ab', 1?: 'xy'}", $x); } - assertType("array{}|array{'xy'}|array{0: 'ab', 1?: 'xy'}", $x); + assertType("array{}|array{'xy'}|list{0: 'ab', 1?: 'xy'}", $x); } } diff --git a/tests/PHPStan/Analyser/nsrt/partial-function-application-replay.php b/tests/PHPStan/Analyser/nsrt/partial-function-application-replay.php index 7bf8f3893b3..7bc6d98de7f 100644 --- a/tests/PHPStan/Analyser/nsrt/partial-function-application-replay.php +++ b/tests/PHPStan/Analyser/nsrt/partial-function-application-replay.php @@ -34,7 +34,7 @@ function bound(\DateTimeImmutable $d, array $arr, string $s): void $pm = preg_match('/(a)(b)?/', ?, ...); $pm('ab', $mm); - assertType("array{}|array{0: non-falsy-string, 1: 'a', 2?: 'b'}", $mm); + assertType("array{}|list{0: non-falsy-string, 1: 'a', 2?: 'b'}", $mm); $has = array_key_exists('a', ?); if ($has($arr)) { diff --git a/tests/PHPStan/Analyser/nsrt/php73_functions.php b/tests/PHPStan/Analyser/nsrt/php73_functions.php index 46bcbe50c59..c3b8ce33a7e 100644 --- a/tests/PHPStan/Analyser/nsrt/php73_functions.php +++ b/tests/PHPStan/Analyser/nsrt/php73_functions.php @@ -62,10 +62,10 @@ public function doFoo( assertType('string|null', array_key_last($arrayWithStringKeys)); assertType('null', array_key_first($emptyArray)); assertType('null', array_key_last($emptyArray)); - assertType('0|1|2', array_key_first($literalArray)); - assertType('0|1|2', array_key_last($literalArray)); - assertType('0|1|2|3', array_key_first($anotherLiteralArray)); - assertType('0|1|2|3', array_key_last($anotherLiteralArray)); + assertType('0', array_key_first($literalArray)); + assertType('2', array_key_last($literalArray)); + assertType('0', array_key_first($anotherLiteralArray)); + assertType('2|3', array_key_last($anotherLiteralArray)); assertType('\'a\'|\'b\'|\'c\'', array_key_first($constantArrayOptionalKeys1)); assertType('\'a\'|\'b\'|\'c\'', array_key_last($constantArrayOptionalKeys1)); assertType('\'a\'|\'b\'|\'c\'', array_key_first($constantArrayOptionalKeys2)); diff --git a/tests/PHPStan/Analyser/nsrt/preg_match_all_shapes.php b/tests/PHPStan/Analyser/nsrt/preg_match_all_shapes.php index 93099323c1b..67366fceefe 100644 --- a/tests/PHPStan/Analyser/nsrt/preg_match_all_shapes.php +++ b/tests/PHPStan/Analyser/nsrt/preg_match_all_shapes.php @@ -71,7 +71,7 @@ function (string $size): void { function (string $size): void { preg_match_all('/a(b)(\d+)?/', $size, $matches, PREG_SET_ORDER); - assertType("list", $matches); + assertType("list", $matches); }; function (string $size): void { @@ -195,7 +195,7 @@ function bug11661(): void { assertType("list", $results); preg_match_all('/(ERR)?.+/', 'abc', $results, PREG_SET_ORDER); - assertType("list", $results); + assertType("list", $results); } diff --git a/tests/PHPStan/Analyser/nsrt/preg_match_shapes.php b/tests/PHPStan/Analyser/nsrt/preg_match_shapes.php index 290e2673bb0..41204e56f45 100644 --- a/tests/PHPStan/Analyser/nsrt/preg_match_shapes.php +++ b/tests/PHPStan/Analyser/nsrt/preg_match_shapes.php @@ -39,9 +39,9 @@ function doMatch(string $s): void { assertType('array{}|array{non-falsy-string, non-empty-string}', $matches); if (preg_match('/(a)(b)*(c)(d)*/', $s, $matches)) { - assertType("array{0: non-falsy-string, 1: 'a', 2: string, 3: 'c', 4?: non-empty-string}", $matches); + assertType("list{0: non-falsy-string, 1: 'a', 2: string, 3: 'c', 4?: non-empty-string}", $matches); } - assertType("array{}|array{0: non-falsy-string, 1: 'a', 2: string, 3: 'c', 4?: non-empty-string}", $matches); + assertType("array{}|list{0: non-falsy-string, 1: 'a', 2: string, 3: 'c', 4?: non-empty-string}", $matches); if (preg_match('/(a)(?b)*(c)(d)*/', $s, $matches)) { assertType("array{0: non-falsy-string, 1: 'a', name: string, 2: string, 3: 'c', 4?: non-empty-string}", $matches); @@ -54,9 +54,9 @@ function doMatch(string $s): void { assertType("array{}|array{0: non-falsy-string, 1: 'a', 2: string, 3: 'c', name?: non-empty-string, 4?: non-empty-string}", $matches); if (preg_match('/(a|b)|(?:c)/', $s, $matches)) { - assertType("array{0: non-empty-string, 1?: 'a'|'b'}", $matches); + assertType("list{0: non-empty-string, 1?: 'a'|'b'}", $matches); } - assertType("array{}|array{0: non-empty-string, 1?: 'a'|'b'}", $matches); + assertType("array{}|list{0: non-empty-string, 1?: 'a'|'b'}", $matches); if (preg_match('/(foo)(bar)(baz)+/', $s, $matches)) { assertType("array{non-falsy-string, 'foo', 'bar', non-falsy-string}", $matches); @@ -64,19 +64,19 @@ function doMatch(string $s): void { assertType("array{}|array{non-falsy-string, 'foo', 'bar', non-falsy-string}", $matches); if (preg_match('/(foo)(bar)(baz)*/', $s, $matches)) { - assertType("array{0: non-falsy-string, 1: 'foo', 2: 'bar', 3?: non-falsy-string}", $matches); + assertType("list{0: non-falsy-string, 1: 'foo', 2: 'bar', 3?: non-falsy-string}", $matches); } - assertType("array{}|array{0: non-falsy-string, 1: 'foo', 2: 'bar', 3?: non-falsy-string}", $matches); + assertType("array{}|list{0: non-falsy-string, 1: 'foo', 2: 'bar', 3?: non-falsy-string}", $matches); if (preg_match('/(foo)(bar)(baz)?/', $s, $matches)) { - assertType("array{0: non-falsy-string, 1: 'foo', 2: 'bar', 3?: 'baz'}", $matches); + assertType("list{0: non-falsy-string, 1: 'foo', 2: 'bar', 3?: 'baz'}", $matches); } - assertType("array{}|array{0: non-falsy-string, 1: 'foo', 2: 'bar', 3?: 'baz'}", $matches); + assertType("array{}|list{0: non-falsy-string, 1: 'foo', 2: 'bar', 3?: 'baz'}", $matches); if (preg_match('/(foo)(bar)(baz){0,3}/', $s, $matches)) { - assertType("array{0: non-falsy-string, 1: 'foo', 2: 'bar', 3?: non-falsy-string}", $matches); + assertType("list{0: non-falsy-string, 1: 'foo', 2: 'bar', 3?: non-falsy-string}", $matches); } - assertType("array{}|array{0: non-falsy-string, 1: 'foo', 2: 'bar', 3?: non-falsy-string}", $matches); + assertType("array{}|list{0: non-falsy-string, 1: 'foo', 2: 'bar', 3?: non-falsy-string}", $matches); if (preg_match('/(foo)(bar)(baz){2,3}/', $s, $matches)) { assertType("array{non-falsy-string, 'foo', 'bar', non-falsy-string}", $matches); @@ -236,7 +236,7 @@ function doFoo(string $row): void assertType("array{non-falsy-string, 'ab', 'b'}", $matches); } if (preg_match('~^(a(b)?)$~', $row, $matches) === 1) { - assertType("array{0: non-falsy-string, 1: 'a'|'ab', 2?: 'b'}", $matches); + assertType("list{0: non-falsy-string, 1: 'a'|'ab', 2?: 'b'}", $matches); } if (preg_match('~^(a(b)?)?$~', $row, $matches) === 1) { assertType("list{0: string, 1?: 'a'|'ab', 2?: 'b'}", $matches); @@ -279,7 +279,7 @@ function (string $size): void { if (preg_match('~^a\.b(c(\d+)?)d~', $size, $matches) !== 1) { throw new InvalidArgumentException(sprintf('Invalid size "%s"', $size)); } - assertType('array{0: non-falsy-string, 1: non-falsy-string, 2?: numeric-string}', $matches); + assertType('list{0: non-falsy-string, 1: non-falsy-string, 2?: numeric-string}', $matches); }; function (string $size): void { @@ -328,7 +328,7 @@ function (string $size): void { function bug11277a(string $value): void { if (preg_match('/^\[(.+,?)*\]$/', $value, $matches)) { - assertType('array{0: non-falsy-string, 1?: non-empty-string}', $matches); + assertType('list{0: non-falsy-string, 1?: non-empty-string}', $matches); if (count($matches) === 2) { assertType('array{non-falsy-string, non-empty-string}', $matches); } @@ -338,7 +338,7 @@ function bug11277a(string $value): void function bug11277b(string $value): void { if (preg_match('/^(?:(.+,?)|(x))*$/', $value, $matches)) { - assertType("array{0: string, 1?: non-empty-string}|array{string, '', non-empty-string}", $matches); + assertType("array{string, '', non-empty-string}|list{0: string, 1?: non-empty-string}", $matches); } } @@ -411,11 +411,11 @@ function (string $s): void { function (string $s): void { if (preg_match('{' . preg_quote($s) . '(z)' . preg_quote($s) . '(?:abc)(def)?}', $s, $matches)) { - assertType("array{0: non-falsy-string, 1: 'z', 2?: 'def'}", $matches); + assertType("list{0: non-falsy-string, 1: 'z', 2?: 'def'}", $matches); } else { assertType('array{}', $matches); } - assertType("array{}|array{0: non-falsy-string, 1: 'z', 2?: 'def'}", $matches); + assertType("array{}|list{0: non-falsy-string, 1: 'z', 2?: 'def'}", $matches); }; function (string $s, $mixed): void { @@ -679,13 +679,13 @@ function (string $s): void { function (string $value): void { if (preg_match('/^(x)*$/', $value, $matches, PREG_OFFSET_CAPTURE)) { - assertType("array{0: array{string, int<-1, max>}, 1?: array{non-empty-string, int<-1, max>}}", $matches); + assertType("list{0: array{string, int<-1, max>}, 1?: array{non-empty-string, int<-1, max>}}", $matches); } }; function (string $value): void { if (preg_match('/^(?:(x)|(y))*$/', $value, $matches, PREG_OFFSET_CAPTURE)) { - assertType("array{0: array{string, int<-1, max>}, 1?: array{non-empty-string, int<-1, max>}}|array{array{string, int<-1, max>}, array{'', int<-1, max>}, array{non-empty-string, int<-1, max>}}", $matches); + assertType("array{array{string, int<-1, max>}, array{'', int<-1, max>}, array{non-empty-string, int<-1, max>}}|list{0: array{string, int<-1, max>}, 1?: array{non-empty-string, int<-1, max>}}", $matches); } }; @@ -712,7 +712,7 @@ static public function sayHello(string $source): void function (string $s): void { if (preg_match('~a|(\d)|(\s)~', $s, $matches) === 1) { - assertType("array{0: non-empty-string, 1?: numeric-string}|array{non-empty-string, '', non-empty-string}", $matches); + assertType("array{non-empty-string, '', non-empty-string}|list{0: non-empty-string, 1?: numeric-string}", $matches); } }; @@ -724,13 +724,13 @@ function (string $s): void { function (string $s): void { if (preg_match('~a|(\d)|(\s)~', $s, $matches, PREG_OFFSET_CAPTURE) === 1) { - assertType("array{0: array{non-empty-string, int<-1, max>}, 1?: array{numeric-string, int<-1, max>}}|array{array{non-empty-string, int<-1, max>}, array{'', int<-1, max>}, array{non-empty-string, int<-1, max>}}", $matches); + assertType("array{array{non-empty-string, int<-1, max>}, array{'', int<-1, max>}, array{non-empty-string, int<-1, max>}}|list{0: array{non-empty-string, int<-1, max>}, 1?: array{numeric-string, int<-1, max>}}", $matches); } }; function (string $s): void { preg_match('~a|(\d)|(\s)~', $s, $matches); - assertType("array{}|array{0: non-empty-string, 1?: numeric-string}|array{non-empty-string, '', non-empty-string}", $matches); + assertType("array{}|array{non-empty-string, '', non-empty-string}|list{0: non-empty-string, 1?: numeric-string}", $matches); }; function bug11490 (string $expression): void { @@ -915,23 +915,23 @@ function bugEmptySubexpression (string $string): void { } if (preg_match('~|(a)~', $string, $matches)) { - assertType("array{0: string, 1?: 'a'}", $matches); + assertType("list{0: string, 1?: 'a'}", $matches); } if (preg_match('~(a)|~', $string, $matches)) { - assertType("array{0: string, 1?: 'a'}", $matches); + assertType("list{0: string, 1?: 'a'}", $matches); } if (preg_match('~(a)||(b)~', $string, $matches)) { - assertType("array{0: string, 1?: 'a'}|array{string, '', 'b'}", $matches); + assertType("array{string, '', 'b'}|list{0: string, 1?: 'a'}", $matches); } if (preg_match('~(|(a))~', $string, $matches)) { - assertType("array{0: string, 1: ''|'a', 2?: 'a'}", $matches); + assertType("list{0: string, 1: ''|'a', 2?: 'a'}", $matches); } if (preg_match('~((a)|)~', $string, $matches)) { - assertType("array{0: string, 1: ''|'a', 2?: 'a'}", $matches); + assertType("list{0: string, 1: ''|'a', 2?: 'a'}", $matches); } if (preg_match('~((a)||(b))~', $string, $matches)) { @@ -948,17 +948,17 @@ function bug11744(string $string): void if (!preg_match('~^((/[a-z]+)?)~', $string, $matches)) { return; } - assertType('array{0: string, 1: string, 2?: non-falsy-string}', $matches); + assertType('list{0: string, 1: string, 2?: non-falsy-string}', $matches); if (!preg_match('~^((/[a-z]+)?.*)~', $string, $matches)) { return; } - assertType('array{0: string, 1: string, 2?: non-falsy-string}', $matches); + assertType('list{0: string, 1: string, 2?: non-falsy-string}', $matches); if (!preg_match('~^((/[a-z]+)?.+)~', $string, $matches)) { return; } - assertType('array{0: non-empty-string, 1: non-empty-string, 2?: non-falsy-string}', $matches); + assertType('list{0: non-empty-string, 1: non-empty-string, 2?: non-falsy-string}', $matches); } function bug12749(string $str): void @@ -1114,7 +1114,7 @@ function testAssertionsAreZeroWidth(string $s): void { function testGroupsInNegativeAssertionsAreNeverSet(string $s): void { // from PCRE2 testdata/testinput1 if (preg_match('/(?', range($float, 5, $integer)); assertType('non-empty-list<(float|int|string)>', range($float, $mixed, $integer)); assertType('non-empty-list<(float|int|string)>', range($integer, $mixed)); -assertType('array{0: 1, 1?: 2}', range(1, doFoo() ? 1 : 2)); -assertType('array{0: -1, 1: 0, 2: 1, 3?: 2}|array{0: 1, 1?: 2}', range(doFoo() ? -1 : 1, doFoo() ? 1 : 2)); +assertType('list{0: 1, 1?: 2}', range(1, doFoo() ? 1 : 2)); +assertType('list{0: -1, 1: 0, 2: 1, 3?: 2}|list{0: 1, 1?: 2}', range(doFoo() ? -1 : 1, doFoo() ? 1 : 2)); assertType('array{3, 2, 1, 0, -1}', range(3, -1)); assertType('non-empty-list>', range(0, 50)); diff --git a/tests/PHPStan/Analyser/nsrt/ternary-assign-condition-narrows-variable.php b/tests/PHPStan/Analyser/nsrt/ternary-assign-condition-narrows-variable.php index bb139eb32c3..1650db7651e 100644 --- a/tests/PHPStan/Analyser/nsrt/ternary-assign-condition-narrows-variable.php +++ b/tests/PHPStan/Analyser/nsrt/ternary-assign-condition-narrows-variable.php @@ -34,7 +34,7 @@ function countVerdict(string $payload, bool $withImages): void if (count($parts) !== $lines) { return; } - assertType('array{0: string, 1: string, 2: string, 3: string, 4?: string}', $parts); + assertType('list{0: string, 1: string, 2: string, 3: string, 4?: string}', $parts); if ($withImages) { assertType('5', $lines); diff --git a/tests/PHPStan/Analyser/nsrt/unsealed-derivations.php b/tests/PHPStan/Analyser/nsrt/unsealed-derivations.php index 1766ba6e54b..bf70a5a322e 100644 --- a/tests/PHPStan/Analyser/nsrt/unsealed-derivations.php +++ b/tests/PHPStan/Analyser/nsrt/unsealed-derivations.php @@ -383,12 +383,12 @@ class PopArray public function popMakesLastKeyOptional(array $arr): void { array_pop($arr); - // `array_pop` removes the last element. With unsealed extras, the - // last element might be one of those extras (the unsealed slot - // silently shrinks by one) or — if no extras existed — the last - // explicit key. So the last explicit key becomes optional and - // the unsealed slot is preserved (still "zero or more"). - assertType('array{a: 1, b?: 2, ...}', $arr); + // `array_pop` removes the last element. A PHPDoc shape does not + // say in which order its keys come, so the last element can be + // any explicit key or one of the extras. Every explicit key + // becomes optional and the unsealed slot is preserved (still + // "zero or more"). + assertType('array{a?: 1, b?: 2, ...}', $arr); } } @@ -402,11 +402,11 @@ class ShiftArray public function shiftPreservesUnsealed(array $arr): void { array_shift($arr); - // `array_shift` removes the first element. With explicit keys in - // place, that's always the leading explicit key (`a`). The - // unsealed extras live "after" the explicit ones and are - // preserved. - assertType('array{b: 2, ...}', $arr); + // `array_shift` removes the first element. A PHPDoc shape does + // not say in which order its keys come, so the first element can + // be any explicit key or one of the extras. Every explicit key + // becomes optional and the unsealed slot is preserved. + assertType('array{a?: 1, b?: 2, ...}', $arr); } } @@ -419,12 +419,14 @@ class ArrayKeysValues */ public function keysFromUnsealed(array $arr): void { - // `array_keys` returns a list of the source's keys. Explicit - // keys land in the result's value slots; the source's unsealed - // *key* type fills the new unsealed value slot. The result is - // list-shaped, so its unsealed key range is `int<0, max>` (the - // describe collapses that to the `` short form). - assertType("array{'a', 'b', ...}", array_keys($arr)); + // `array_keys` returns a list of the source's keys. A PHPDoc + // shape does not say in which order its keys come, and the + // extras can come before the explicit keys, so every position + // holds any explicit key or the source's unsealed *key* type. + // The result is list-shaped, so its unsealed key range is + // `int<0, max>` (the describe collapses that to the `` + // short form). + assertType("array{'a'|'b'|int, 'a'|'b'|int, ...}", array_keys($arr)); } /** @@ -432,10 +434,11 @@ public function keysFromUnsealed(array $arr): void */ public function valuesFromUnsealed(array $arr): void { - // `array_values` returns a list of the source's values. The - // source's unsealed *value* type fills the new unsealed value - // slot. - assertType('array{1, 2, ...}', array_values($arr)); + // `array_values` returns a list of the source's values. The keys + // come in any order and the extras can come first, so every + // position holds any explicit value or the source's unsealed + // *value* type, which also fills the new unsealed value slot. + assertType('array{1|2|string, 1|2|string, ...}', array_values($arr)); } /** @@ -444,8 +447,8 @@ public function valuesFromUnsealed(array $arr): void public function keysFromUnsealedWithStringKeys(array $arr): void { // Source's unsealed key type is `string`, so the result's - // unsealed values are strings. - assertType("array{'a', 'b', ...}", array_keys($arr)); + // values are strings at every position. + assertType("array{string, string, ...}", array_keys($arr)); } } @@ -458,9 +461,10 @@ class SliceArray */ public function sliceWithinExplicit(array $arr): void { - // Slice fits entirely within the explicit keys — the unsealed - // slot doesn't come into play and the result is sealed. - assertType("array{a: 1}", array_slice($arr, 0, 1)); + // The keys come in any order, so the first element can be any + // explicit key or one of the extras: every explicit key becomes + // optional and the extras slot stays. + assertType("array{a?: 1, b?: 2, ...}", array_slice($arr, 0, 1)); } /** @@ -468,10 +472,10 @@ public function sliceWithinExplicit(array $arr): void */ public function sliceBeyondExplicit(array $arr): void { - // Slice extends past the explicit keys: the trailing positions - // could be filled by unsealed extras (or be absent), so the - // result is unsealed and carries the source's extras slot. - assertType('array{a: 1, b: 2, ...}', array_slice($arr, 0, 5)); + // Slice extends past the explicit keys: any of them, and any + // extras, could be included (or be absent), so the result is + // unsealed and carries the source's extras slot. + assertType('array{a?: 1, b?: 2, ...}', array_slice($arr, 0, 5)); } } diff --git a/tests/PHPStan/PhpDoc/TypeDescriptionTest.php b/tests/PHPStan/PhpDoc/TypeDescriptionTest.php index 5df9b9572fc..e418b60240a 100644 --- a/tests/PHPStan/PhpDoc/TypeDescriptionTest.php +++ b/tests/PHPStan/PhpDoc/TypeDescriptionTest.php @@ -58,6 +58,7 @@ public static function dataTest(): iterable $builder = ConstantArrayTypeBuilder::createEmpty(); $builder->setOffsetValueType(new ConstantStringType('foo'), new IntegerType(), true); $builder->setOffsetValueType(new ConstantStringType('bar'), new StringType()); + $builder->forgetKeyOrder(); yield ['array{foo?: int, bar: string}', $builder->getArray()]; $predicateCallable = static fn (AssertTag $assertTag): CallableType => new CallableType( diff --git a/tests/PHPStan/Rules/Arrays/NonexistentOffsetInArrayDimFetchRuleTest.php b/tests/PHPStan/Rules/Arrays/NonexistentOffsetInArrayDimFetchRuleTest.php index 30752f56b18..b07d4d3f280 100644 --- a/tests/PHPStan/Rules/Arrays/NonexistentOffsetInArrayDimFetchRuleTest.php +++ b/tests/PHPStan/Rules/Arrays/NonexistentOffsetInArrayDimFetchRuleTest.php @@ -908,7 +908,7 @@ public function testArrayDimFetchOnArrayKeyFirsOrLastOrCount(): void $this->analyse([__DIR__ . '/data/array-dim-fetch-on-array-key-first-last.php'], [ [ - 'Offset int<0, max>|null might not exist on list.', + 'Offset 0|null might not exist on list.', 12, ], [ diff --git a/tests/PHPStan/Rules/Comparison/ImpossibleCheckTypeFunctionCallRuleTest.php b/tests/PHPStan/Rules/Comparison/ImpossibleCheckTypeFunctionCallRuleTest.php index 1319a5ab2ce..f8d9fae9727 100644 --- a/tests/PHPStan/Rules/Comparison/ImpossibleCheckTypeFunctionCallRuleTest.php +++ b/tests/PHPStan/Rules/Comparison/ImpossibleCheckTypeFunctionCallRuleTest.php @@ -132,7 +132,7 @@ public function testImpossibleCheckTypeFunctionCall(): void 331, ], [ - 'Call to function in_array() with arguments \'baz\', array{0: \'bar\', 1?: \'foo\'} and true will always evaluate to false.', + 'Call to function in_array() with arguments \'baz\', list{0: \'bar\', 1?: \'foo\'} and true will always evaluate to false.', 347, ], [ @@ -1305,4 +1305,21 @@ public function testBug15147(): void $this->analyse([__DIR__ . '/../Arrays/data/bug-15147.php'], []); } + #[RequiresPhp('>= 8.1.0')] + public function testBug12725(): void + { + $this->analyse([__DIR__ . '/data/bug-12725.php'], [ + [ + 'Call to function array_is_list() with array{a: string, 0: string, 1: string} will always evaluate to false.', + 22, + 'Because the type is coming from a PHPDoc, you can turn off this check by setting treatPhpDocTypesAsCertain: false in your %configurationFile%.', + ], + [ + 'Call to function array_is_list() with array{-1: string, 0: string, 1: string} will always evaluate to false.', + 28, + 'Because the type is coming from a PHPDoc, you can turn off this check by setting treatPhpDocTypesAsCertain: false in your %configurationFile%.', + ], + ]); + } + } diff --git a/tests/PHPStan/Rules/Comparison/StrictComparisonOfDifferentTypesRuleTest.php b/tests/PHPStan/Rules/Comparison/StrictComparisonOfDifferentTypesRuleTest.php index 4a5cc8d687f..1907ae9cd08 100644 --- a/tests/PHPStan/Rules/Comparison/StrictComparisonOfDifferentTypesRuleTest.php +++ b/tests/PHPStan/Rules/Comparison/StrictComparisonOfDifferentTypesRuleTest.php @@ -1357,4 +1357,19 @@ public function testSessionLifecycle(): void $this->analyse([__DIR__ . '/data/session-lifecycle.php'], []); } + public function testBug12725(): void + { + $this->analyse([__DIR__ . '/data/bug-12725b.php'], [ + [ + 'Strict comparison using === between array{a: 1, b: \'foo\'} and array{b: \'foo\', a: 1} will always evaluate to false.', + 9, + ], + ]); + } + + public function testBug14940(): void + { + $this->analyse([__DIR__ . '/data/bug-14940.php'], []); + } + } diff --git a/tests/PHPStan/Rules/Comparison/data/bug-12725.php b/tests/PHPStan/Rules/Comparison/data/bug-12725.php new file mode 100644 index 00000000000..b597848d7bb --- /dev/null +++ b/tests/PHPStan/Rules/Comparison/data/bug-12725.php @@ -0,0 +1,48 @@ += 8.0 + +declare(strict_types = 1); + +namespace Bug12725; + +class HelloWorld +{ + /** + * @param array{a?: string, 0: string, 1: string} $a + * @param array{a: string, 0: string, 1: string} $b + * @param array{-1?: string, 0: string, 1: string} $c + * @param array{-1: string, 0: string, 1: string} $d + * @param array{0: string, 1: string} $e + * @param array{1: string, 0: string} $f + */ + public function sayHello(array $a, array $b, array $c, array $d, array $e, array $f): void + { + if (array_is_list($a)) { // maybe a list - should *not* be reported + + } + if (array_is_list($b)) { // can't be a list - reported + + } + if (array_is_list($c)) { // maybe a list - should *not* be reported + + } + if (array_is_list($d)) { // can't be a list - reported + + } + if (array_is_list($e)) { // maybe a list - should *not* be reported + + } + if (array_is_list($f)) { // maybe a list - should *not* be reported + + } + } +} + +(new HelloWorld)->sayHello( + a: ['x', 'y'], // a list + b: ['x', 'y', 'a' => 'a'], // not a list + c: ['x', 'y'], // a list + d: ['x', 'y', -1 => 'z'], // not a list + e: [1 => 'x', 0 => 'y'], // not a list + f: [0 => 'x', 1 => 'y'], // not a list +); + diff --git a/tests/PHPStan/Rules/Comparison/data/bug-12725b.php b/tests/PHPStan/Rules/Comparison/data/bug-12725b.php new file mode 100644 index 00000000000..116e88fafe8 --- /dev/null +++ b/tests/PHPStan/Rules/Comparison/data/bug-12725b.php @@ -0,0 +1,22 @@ + 1, 'b' => 'foo'] === ['b' => 'foo', 'a' => 1]; + } + + /** @param array{b: string, a: int} $b */ + public function sayHello2(array $b): void + { + $a = ['a' => 1, 'b' => 'foo'] === $b; + } + + public function sayHello3(): void + { + $this->sayHello2(['a' => 1, 'b' => 'foo']); // no error + } +} diff --git a/tests/PHPStan/Rules/Comparison/data/bug-14940.php b/tests/PHPStan/Rules/Comparison/data/bug-14940.php new file mode 100644 index 00000000000..e2bcd692438 --- /dev/null +++ b/tests/PHPStan/Rules/Comparison/data/bug-14940.php @@ -0,0 +1,19 @@ + 2, 'foo' => 1]) === ['qux', 'foo'] -> $keys[1] === 'foo' is TRUE +f(['qux' => 2, 'foo' => 1]); + diff --git a/tests/PHPStan/Rules/Functions/CallToFunctionParametersRuleTest.php b/tests/PHPStan/Rules/Functions/CallToFunctionParametersRuleTest.php index a043b865ba6..6bea9916874 100644 --- a/tests/PHPStan/Rules/Functions/CallToFunctionParametersRuleTest.php +++ b/tests/PHPStan/Rules/Functions/CallToFunctionParametersRuleTest.php @@ -4024,4 +4024,14 @@ public function testRecursiveBuiltinParameters(): void $this->analyse([__DIR__ . '/data/recursive-builtin-parameters.php'], $errors); } + public function testBug12725(): void + { + $this->analyse([__DIR__ . '/data/bug-12725.php'], [ + [ + 'Parameter #1 $a of function Bug12725\\f expects array{bool, string}, array{1: \'yyy\', 0: false} given.', + 17, + ], + ]); + } + } diff --git a/tests/PHPStan/Rules/Functions/ReturnTypeRuleNoBleedingEdgeTest.php b/tests/PHPStan/Rules/Functions/ReturnTypeRuleNoBleedingEdgeTest.php new file mode 100644 index 00000000000..b79d55468f2 --- /dev/null +++ b/tests/PHPStan/Rules/Functions/ReturnTypeRuleNoBleedingEdgeTest.php @@ -0,0 +1,49 @@ + + */ +class ReturnTypeRuleNoBleedingEdgeTest extends RuleTestCase +{ + + protected function getRule(): Rule + { + return new ReturnTypeRule(new FunctionReturnTypeCheck( + new RuleLevelHelper( + self::createReflectionProvider(), + checkNullables: true, + checkThisOnly: false, + checkUnionTypes: true, + checkExplicitMixed: false, + checkImplicitMixed: false, + checkBenevolentUnionTypes: false, + discoveringSymbolsTip: true, + ), + )); + } + + #[Override] + public static function getAdditionalConfigFiles(): array + { + return []; + } + + public function testBug15908(): void + { + $this->analyse([__DIR__ . '/data/bug-15908.php'], [ + [ + 'Function Bug15908\\differentValueType() should return Bug15908\\Box but returns Bug15908\\Box.', + 28, + ], + ]); + } + +} diff --git a/tests/PHPStan/Rules/Functions/data/bug-12725.php b/tests/PHPStan/Rules/Functions/data/bug-12725.php new file mode 100644 index 00000000000..4e255748859 --- /dev/null +++ b/tests/PHPStan/Rules/Functions/data/bug-12725.php @@ -0,0 +1,18 @@ + 'yyy', 0 => false])); + diff --git a/tests/PHPStan/Rules/Functions/data/bug-15908.php b/tests/PHPStan/Rules/Functions/data/bug-15908.php new file mode 100644 index 00000000000..84a486ddd88 --- /dev/null +++ b/tests/PHPStan/Rules/Functions/data/bug-15908.php @@ -0,0 +1,29 @@ +v = $v; } +} + +/** + * @param array{a: int, t: int} $r + * @return Box + */ +function f(array $r): Box { + $v = ['t' => (string) $r['t']] + $r; + return new Box($v); +} + +/** + * @param array{a: int, t: int} $r + * @return Box + */ +function differentValueType(array $r): Box { + $v = ['t' => (string) $r['t']] + $r; + return new Box($v); +} diff --git a/tests/PHPStan/Rules/Variables/IssetRuleTest.php b/tests/PHPStan/Rules/Variables/IssetRuleTest.php index d699fd96433..eafe4060d27 100644 --- a/tests/PHPStan/Rules/Variables/IssetRuleTest.php +++ b/tests/PHPStan/Rules/Variables/IssetRuleTest.php @@ -563,7 +563,7 @@ public function testIssetConstantArray(): void $this->analyse([__DIR__ . '/data/isset-constant-array.php'], [ [ - 'Offset 2 on array{0: string, 1: string, 2: string, 3: string, 4?: string} in isset() always exists and is not nullable.', + 'Offset 2 on list{0: string, 1: string, 2: string, 3: string, 4?: string} in isset() always exists and is not nullable.', 13, ], [ diff --git a/tests/PHPStan/Type/Constant/ConstantArrayTypeBuilderTest.php b/tests/PHPStan/Type/Constant/ConstantArrayTypeBuilderTest.php index 8a4bf9ca9c5..b645d86e264 100644 --- a/tests/PHPStan/Type/Constant/ConstantArrayTypeBuilderTest.php +++ b/tests/PHPStan/Type/Constant/ConstantArrayTypeBuilderTest.php @@ -172,6 +172,46 @@ public function testIsList(): void $this->assertFalse($builder->isList()); } + public function testKeyOrder(): void + { + BleedingEdgeToggle::withBleedingEdge(true, function (): void { + $a = new ConstantStringType('a'); + $b = new ConstantStringType('b'); + + $builder = ConstantArrayTypeBuilder::createEmpty(); + $builder->setOffsetValueType($a, new IntegerType()); + $builder->setOffsetValueType($b, new IntegerType()); + $unordered = $builder->getArray(); + $this->assertInstanceOf(ConstantArrayType::class, $unordered); + $this->assertFalse($unordered->isKeyOrderKnown()); + + $builder->makeKeyOrderKnown(); + $ordered = $builder->getArray(); + $this->assertInstanceOf(ConstantArrayType::class, $ordered); + $this->assertTrue($ordered->isKeyOrderKnown()); + + // a builder started from an array keeps what it knows about the order + foreach ([$unordered, $ordered] as $start) { + $builder = ConstantArrayTypeBuilder::createFromConstantArray($start); + $builder->setOffsetValueType(new ConstantStringType('c'), new IntegerType()); + $array = $builder->getArray(); + $this->assertInstanceOf(ConstantArrayType::class, $array); + $this->assertSame($start->isKeyOrderKnown(), $array->isKeyOrderKnown()); + } + + // values appended in no known order make a list only maybe + $builder = ConstantArrayTypeBuilder::createEmpty(); + $builder->setOffsetValueType(null, new IntegerType()); + $builder->setOffsetValueType(null, new StringType()); + $this->assertFalse($builder->isList()); + $this->assertSame('Maybe', $builder->getArray()->isList()->describe()); + + $builder->makeKeyOrderKnown(); + $this->assertTrue($builder->isList()); + $this->assertSame('Yes', $builder->getArray()->isList()->describe()); + }); + } + public function testIsListWithUnion(): void { $builder = ConstantArrayTypeBuilder::createEmpty(); diff --git a/tests/PHPStan/Type/Constant/ConstantArrayTypeTest.php b/tests/PHPStan/Type/Constant/ConstantArrayTypeTest.php index 810a5b6a3e2..50176ddfd1a 100644 --- a/tests/PHPStan/Type/Constant/ConstantArrayTypeTest.php +++ b/tests/PHPStan/Type/Constant/ConstantArrayTypeTest.php @@ -642,6 +642,48 @@ public function testAccepts(Type $type, Type $otherType, TrinaryLogic $expectedR $this->assertSame($reasons, $actualResult->reasons, $testDescription); } + public function testKeyOrder(): void + { + $a = new ConstantStringType('a'); + $b = new ConstantStringType('b'); + $int = new IntegerType(); + $abOrdered = new ConstantArrayType([$a, $b], [$int, $int]); + $baOrdered = new ConstantArrayType([$b, $a], [$int, $int]); + $abUnordered = $abOrdered->forgetKeyOrder(); + $baUnordered = $baOrdered->forgetKeyOrder(); + + // a shape that does not know its key order covers every order of its keys + $this->assertTrue($abUnordered->isSuperTypeOf($baOrdered)->yes()); + $this->assertTrue($abUnordered->isSuperTypeOf($abOrdered)->yes()); + $this->assertTrue($baOrdered->isSuperTypeOf($abUnordered)->maybe()); + $this->assertTrue($abUnordered->accepts($baOrdered, true)->yes()); + $this->assertTrue($abUnordered->equals($baUnordered)); + $this->assertFalse($abUnordered->equals($abOrdered)); + $this->assertFalse($abOrdered->equals($baOrdered)); + + $this->assertSame('array{a: int, b: int}(unordered)', TypeCombinator::union($abUnordered, $baOrdered)->describe(VerbosityLevel::cache())); + $this->assertSame('array{a: int, b: int}(unordered)', TypeCombinator::union($baOrdered, $abUnordered)->describe(VerbosityLevel::cache())); + $this->assertSame('array{b: int, a: int}', TypeCombinator::intersect($abUnordered, $baOrdered)->describe(VerbosityLevel::cache())); + $this->assertSame('array{b: int, a: int}', TypeCombinator::intersect($baOrdered, $abUnordered)->describe(VerbosityLevel::cache())); + $this->assertSame('array{a: int, b: int}(unordered)', TypeCombinator::remove($abUnordered, $baOrdered)->describe(VerbosityLevel::cache())); + $this->assertInstanceOf(NeverType::class, TypeCombinator::remove($baOrdered, $abUnordered)); + + // a shape that might be a list might also hold 0 and 1 in the other order + $zero = new ConstantIntegerType(0); + $one = new ConstantIntegerType(1); + $maybeList = TrinaryLogic::createMaybe(); + $zeroOneOrdered = new ConstantArrayType([$zero, $one], [$int, $int], [2], isList: $maybeList); + $oneZeroUnordered = new ConstantArrayType([$one, $zero], [$int, $int], [2], isList: $maybeList, keyOrderKnown: false); + $this->assertTrue($zeroOneOrdered->isKeyOrderKnown()); + $this->assertFalse($oneZeroUnordered->isKeyOrderKnown()); + $this->assertTrue($zeroOneOrdered->isSuperTypeOf($oneZeroUnordered)->maybe()); + $this->assertTrue($zeroOneOrdered->accepts($oneZeroUnordered, true)->maybe()); + + // a list holds its keys in their order whether its shape is ordered or not + $list = new ConstantArrayType([$zero, $one], [$int, $int], [2], isList: TrinaryLogic::createYes(), keyOrderKnown: false); + $this->assertTrue($list->isKeyOrderKnown()); + } + public static function dataIsSuperTypeOfWithoutBleedingEdge(): array { // Build the unsealed shapes under an explicit toggle and return one array (no `yield`), @@ -1669,6 +1711,7 @@ public function testSealedness(): void private function buildShape(array $items): ConstantArrayType { $builder = ConstantArrayTypeBuilder::createEmpty(); + $builder->makeKeyOrderKnown(); foreach ($items as [$key, $valueType, $optional]) { $keyType = is_string($key) ? new ConstantStringType($key) : new ConstantIntegerType($key); $builder->setOffsetValueType($keyType, $valueType, $optional); diff --git a/tests/PHPStan/Type/RecursiveTypeTest.php b/tests/PHPStan/Type/RecursiveTypeTest.php index 0fbbd1dc2b9..22b7952b048 100644 --- a/tests/PHPStan/Type/RecursiveTypeTest.php +++ b/tests/PHPStan/Type/RecursiveTypeTest.php @@ -135,7 +135,7 @@ public static function dataFromRepetition(): iterable yield 'nested in itself' => [ 'array{value: int, next: null}', 'array{value: int, next: array{value: int, next: null}|null}', - '__recursive', + '__recursive', ]; yield 'nested twice' => [ 'array{array{1}}', @@ -190,7 +190,7 @@ public function testFromRepetitionNextToAnotherOne(): void $previous = new ConstantArrayType([new ConstantStringType('cells'), new ConstantStringType('next')], [$inner, new NullType()]); $next = new ConstantArrayType([new ConstantStringType('cells'), new ConstantStringType('next')], [$inner, TypeCombinator::union($previous, new NullType())]); $this->assertSame( - '__recursive, next: __recursion|null}>', + '__recursive, next: __recursion|null}>', RecursiveType::fromRepetition($previous, $next)?->describe(VerbosityLevel::cache()), ); } @@ -250,7 +250,7 @@ public static function dataDescribe(): iterable '__recursive', 'array{value: int, next: *RECURSION*|null}', '__recursive', - '__recursive', + '__recursive', ]; yield 'one in another one, referring to both' => [ '__recursive|int>>>>', diff --git a/tests/PHPStan/Type/TypeCombinatorTest.php b/tests/PHPStan/Type/TypeCombinatorTest.php index 1da9324887d..3a1f95b24a3 100644 --- a/tests/PHPStan/Type/TypeCombinatorTest.php +++ b/tests/PHPStan/Type/TypeCombinatorTest.php @@ -65,6 +65,7 @@ use Traversable; use function array_map; use function array_reverse; +use function count; use function get_class; use function implode; use function is_string; @@ -3059,6 +3060,26 @@ public static function dataUnion(): iterable 'array{a: int, b?: string}', ]; + // values that overlap merge the shapes + yield [ + [ + 'array{a: int}', + 'array{a: 1|string}', + ], + ConstantArrayType::class, + 'array{a: int|string}', + ]; + + // a value that meets no value of the other shape keeps the shapes apart in either order + yield [ + [ + 'array{a?: never}', + 'array{a: int|string}', + ], + UnionType::class, + 'array{a: int|string}|array{a?: never}', + ]; + // new behaviour with definitely sealed arrays yield [ [ @@ -3066,7 +3087,7 @@ public static function dataUnion(): iterable 'array{a: int}', ], ConstantArrayType::class, - 'array{a: int, b?: string}', + 'array{a: int, b?: string} (unordered)', ]; yield [ @@ -3075,7 +3096,7 @@ public static function dataUnion(): iterable 'array{a: false}', ], UnionType::class, - 'array{a: false}|array{a: true, b: string}', + 'array{a: false}|array{a: true, b: string} (unordered: array{a: true, b: string})', ]; yield [ @@ -3102,7 +3123,7 @@ public static function dataUnion(): iterable 'array{a: int<0, max>, ...}', ], ConstantArrayType::class, - 'array{a: int, b?: string, ...}', + 'array{a: int, b?: string, ...} (unordered)', ]; yield [ @@ -3129,7 +3150,7 @@ public static function dataUnion(): iterable 'array{b: string, ...}', ], IntersectionType::class, - 'non-empty-array{a?: int, b?: string, ...}', + 'non-empty-array{a?: int, b?: string, ...} (unordered)', ]; yield [ @@ -3497,6 +3518,104 @@ public static function dataUnion(): iterable UnionType::class, 'array{0: array{string}, 1?: int}|array{array{string, string}}', ]; + // literal arrays with the same keys in the same order keep it + yield [ + [ConstantTypeHelper::getTypeFromValue(['a' => 1, 'b' => 2]), ConstantTypeHelper::getTypeFromValue(['a' => 1, 'b' => 3])], + ConstantArrayType::class, + 'array{a: 1, b: 2|3}', + ]; + // literal arrays with the same keys in different orders merge into a shape that does not know the order + yield [ + [ConstantTypeHelper::getTypeFromValue(['a' => 1, 'b' => 2]), ConstantTypeHelper::getTypeFromValue(['b' => 2, 'a' => 1])], + ConstantArrayType::class, + 'array{a: 1, b: 2} (unordered)', + ]; + yield [ + [ConstantTypeHelper::getTypeFromValue(['a' => 1, 'b' => 2]), ConstantTypeHelper::getTypeFromValue(['b' => 3, 'a' => 1])], + ConstantArrayType::class, + 'array{a: 1, b: 2|3} (unordered)', + ]; + yield [ + [ConstantTypeHelper::getTypeFromValue(['a' => 1, 'b' => 2, 'c' => 3]), ConstantTypeHelper::getTypeFromValue(['c' => 3, 'a' => 1, 'b' => 2])], + ConstantArrayType::class, + 'array{a: 1, b: 2, c: 3} (unordered)', + ]; + yield [ + [ConstantTypeHelper::getTypeFromValue([1 => 'a', 0 => 'b']), ConstantTypeHelper::getTypeFromValue(['b', 'a'])], + ConstantArrayType::class, + "array{'b', 'a'} (unordered)", + ]; + // values that differ at two keys keep the arrays apart, each in its own order + yield [ + [ConstantTypeHelper::getTypeFromValue(['a' => 1, 'b' => 2]), ConstantTypeHelper::getTypeFromValue(['b' => 3, 'a' => 4])], + UnionType::class, + 'array{a: 1, b: 2}|array{a: 4, b: 3}', + ]; + yield [ + [ConstantTypeHelper::getTypeFromValue([1, 2]), ConstantTypeHelper::getTypeFromValue([2, 1])], + UnionType::class, + 'array{1, 2}|array{2, 1}', + ]; + // a key only one of them has leaves the shared keys in the order they share + yield [ + [ConstantTypeHelper::getTypeFromValue(['a' => 1, 'b' => 2]), ConstantTypeHelper::getTypeFromValue(['a' => 1, 'b' => 2, 'c' => 3])], + ConstantArrayType::class, + 'array{a: 1, b: 2, c?: 3}', + ]; + yield [ + [ConstantTypeHelper::getTypeFromValue(['a' => 1, 'b' => 2]), ConstantTypeHelper::getTypeFromValue(['b' => 2, 'a' => 1, 'c' => 3])], + ConstantArrayType::class, + 'array{a: 1, b: 2, c?: 3} (unordered)', + ]; + yield [ + [ConstantTypeHelper::getTypeFromValue([1, 2]), ConstantTypeHelper::getTypeFromValue([1])], + ConstantArrayType::class, + 'array{0: 1, 1?: 2}', + ]; + yield [ + [new ConstantArrayType([], []), ConstantTypeHelper::getTypeFromValue(['a' => 1, 'b' => 2]), ConstantTypeHelper::getTypeFromValue(['b' => 2, 'a' => 1])], + UnionType::class, + 'array{}|array{a: 1, b: 2} (unordered: array{a: 1, b: 2})', + ]; + // a shape that holds the other one in another order forgets its own + yield [ + [ + new ConstantArrayType([new ConstantStringType('a'), new ConstantStringType('b')], [new IntegerType(), new IntegerType()]), + ConstantTypeHelper::getTypeFromValue(['b' => 2, 'a' => 1]), + ], + ConstantArrayType::class, + 'array{a: int, b: int} (unordered)', + ]; + yield [ + [ + new ConstantArrayType([new ConstantStringType('a'), new ConstantStringType('b')], [new IntegerType(), new IntegerType()]), + ConstantTypeHelper::getTypeFromValue(['a' => 1, 'b' => 2]), + ], + ConstantArrayType::class, + 'array{a: int, b: int}', + ]; + // a PHPDoc shape does not know the order of its keys + yield [ + [ConstantTypeHelper::getTypeFromValue(['a' => 1, 'b' => 2]), 'array{b: int, a: int}'], + ConstantArrayType::class, + 'array{a: int, b: int} (unordered)', + ]; + yield [ + ['array{a: int, b: string}', 'array{b: string, a: int}'], + ConstantArrayType::class, + 'array{a: int, b: string} (unordered)', + ]; + yield [ + ['array{a: int, b: string}', 'array{b: string, a: int, c: float}'], + ConstantArrayType::class, + 'array{a: int, b: string, c?: float} (unordered)', + ]; + // a list knows the order of its keys + yield [ + ['list{int, string}', ConstantTypeHelper::getTypeFromValue([1, 'a'])], + ConstantArrayType::class, + 'array{int, string}', + ]; } /** A subclass of StringType holding the names of the properties of a class, as Larastan's model property of X. */ @@ -3605,7 +3724,7 @@ public function isSuperTypeOf(Type $type): IsSuperTypeOfResult } /** - * @param list|list $types + * @param list $types * @param class-string $expectedTypeClass */ #[DataProvider('dataUnion')] @@ -3661,7 +3780,7 @@ public static function dataUnionOnBleedingEdge(): iterable yield [['array', 'array'], UnionType::class, 'array|array']; yield [['array', 'array'], UnionType::class, 'array|array']; yield [['array', 'array'], UnionType::class, 'array|array']; - yield [['array', 'array{foo: DateTimeImmutable, bar: int}'], UnionType::class, 'array|array{bar: int, foo: DateTimeImmutable}']; + yield [['array', 'array{foo: DateTimeImmutable, bar: int}'], UnionType::class, 'array|array{bar: int, foo: DateTimeImmutable} (unordered: array{bar: int, foo: DateTimeImmutable})']; yield [['array{...}', 'array{...}'], UnionType::class, 'array|array']; yield [['array{...}', 'array{...}'], UnionType::class, 'array|array']; yield [['array{a: int}', 'array{...}'], UnionType::class, 'array|array{a: int}']; @@ -3698,7 +3817,7 @@ public function testUnionOnBleedingEdge(array $types, string $expectedTypeClass, } /** - * @param list|list $types + * @param list $types * @param class-string $expectedTypeClass */ #[DataProvider('dataUnion')] @@ -5967,7 +6086,7 @@ public static function dataIntersect(): iterable 'array{a: int<0, max>, ...}', ], ConstantArrayType::class, - 'array{a: int<0, max>, b: string}', + 'array{a: int<0, max>, b: string} (unordered)', ]; yield [ @@ -5976,7 +6095,7 @@ public static function dataIntersect(): iterable 'array{a: int<0, max>, ...}', ], ConstantArrayType::class, - 'array{a: int<0, max>, b: string, ...}', + 'array{a: int<0, max>, b: string, ...} (unordered)', ]; // both unsealed, disjoint known keys, default extras — union of known keys @@ -5986,7 +6105,7 @@ public static function dataIntersect(): iterable 'array{b: string, ...}', ], ConstantArrayType::class, - 'array{a: int, b: string, ...}', + 'array{a: int, b: string, ...} (unordered)', ]; // both unsealed, narrower unsealed value on right @@ -6429,10 +6548,42 @@ public static function dataIntersect(): iterable ConstantArrayType::class, 'array{column: string, label?: string, metadata: array{columns: array, dimension: string, metrics: array}, reportData: int}', ]; + // shapes that list the same keys in different orders hold no array together + yield [ + [ + new ConstantArrayType([new ConstantStringType('a'), new ConstantStringType('b')], [new IntegerType(), new IntegerType()]), + ConstantTypeHelper::getTypeFromValue(['b' => 2, 'a' => 1]), + ], + NeverType::class, + '*NEVER*=implicit', + ]; + // the array that knows its key order keeps it + yield [ + ['array{a: int, b: int}', ConstantTypeHelper::getTypeFromValue(['b' => 2, 'a' => 1])], + ConstantArrayType::class, + 'array{a: 1, b: 2}', + ]; + yield [ + [ + 'array{a: int, b?: int, ...}', + new ConstantArrayType([new ConstantStringType('b'), new ConstantStringType('a'), new ConstantStringType('c')], [new IntegerType(), new IntegerType(), new IntegerType()]), + ], + ConstantArrayType::class, + 'array{a: int, b: int, c: int}', + ]; + // keys from shapes that each know their own order only + yield [ + [ + 'array{a: int, ...}', + new ConstantArrayType([new ConstantStringType('b'), new ConstantStringType('c')], [new IntegerType(), new IntegerType()], [0], [], null, [new StringType(), new IntegerType()]), + ], + ConstantArrayType::class, + 'array{a: int, b: int, c: int, ...} (unordered)', + ]; } /** - * @param list|list $types + * @param list $types * @param class-string $expectedTypeClass */ #[DataProvider('dataIntersect')] @@ -6468,7 +6619,7 @@ public function testIntersect( } /** - * @param list|list $types + * @param list $types * @param class-string $expectedTypeClass */ #[DataProvider('dataIntersect')] @@ -6513,6 +6664,20 @@ private static function describeForIntersectTest(Type $type): string return $traverse($type); }); $description = $type->describe(VerbosityLevel::precise()); + $unorderedShapes = []; + $members = $type instanceof UnionType ? $type->getTypes() : [$type]; + foreach ($members as $member) { + $constantArrays = $member->getConstantArrays(); + if (!$member->isConstantArray()->yes() || count($constantArrays) !== 1 || $constantArrays[0]->isKeyOrderKnown()) { + continue; + } + $unorderedShapes[] = $member->describe(VerbosityLevel::precise()); + } + if (count($members) === 1 && $unorderedShapes !== []) { + $description .= ' (unordered)'; + } elseif ($unorderedShapes !== []) { + $description .= sprintf(' (unordered: %s)', implode(', ', $unorderedShapes)); + } if ($type instanceof MixedType) { $description .= $type->isExplicitMixed() ? '=explicit' : '=implicit'; } diff --git a/tests/PHPStan/Type/TypeToPhpDocNodeTest.php b/tests/PHPStan/Type/TypeToPhpDocNodeTest.php index 21949810ba3..4b531ffc255 100644 --- a/tests/PHPStan/Type/TypeToPhpDocNodeTest.php +++ b/tests/PHPStan/Type/TypeToPhpDocNodeTest.php @@ -307,7 +307,7 @@ public static function dataToPhpDocNode(): iterable ], [ new ConstantStringType('foo'), new ConstantStringType('bar'), - ]), + ], isList: TrinaryLogic::createYes()), "array{'foo', 'bar'}", ]; @@ -329,8 +329,8 @@ public static function dataToPhpDocNode(): iterable ], [ new ConstantStringType('foo'), new ConstantStringType('bar'), - ], [2], [1]), - "array{0: 'foo', 1?: 'bar'}", + ], [2], [1], TrinaryLogic::createYes()), + "list{0: 'foo', 1?: 'bar'}", ]; yield [ @@ -485,6 +485,15 @@ public function testToPhpDocNode(Type $type, string $expected): void $typeStringResolver = self::getContainer()->getByType(TypeStringResolver::class); $parsedType = $typeStringResolver->resolve($typeString); + + // an array shape in PHPDoc names its keys without saying in which order they come + $type = TypeTraverser::map($type, static function (Type $type, callable $traverse): Type { + if ($type instanceof ConstantArrayType) { + $type = $type->forgetKeyOrder(); + } + + return $traverse($type); + }); $this->assertTrue($type->equals($parsedType), sprintf('%s->equals(%s)', $type->describe(VerbosityLevel::precise()), $parsedType->describe(VerbosityLevel::precise()))); } diff --git a/turbo-ext/src/ArrayType.cpp b/turbo-ext/src/ArrayType.cpp index 04f8ac43d2d..4e6c6fab11d 100644 --- a/turbo-ext/src/ArrayType.cpp +++ b/turbo-ext/src/ArrayType.cpp @@ -1253,6 +1253,7 @@ class ArrayType { zv::Val builder = pt_constant_array_type_builder_create_empty(); if (UNEXPECTED(builder.isUndef())) return zv::Val(); + if (UNEXPECTED(!pt_constant_array_type_builder_keep_key_order_of(builder.raw(), constantArray))) return zv::Val(); zv::Val valueType = thisGetIterableValueType(); zv::Val keyType = thisGetIterableKeyType(); if (UNEXPECTED(valueType.isUndef() || keyType.isUndef())) return zv::Val(); diff --git a/turbo-ext/src/ConstantArrayType.cpp b/turbo-ext/src/ConstantArrayType.cpp index eb4aa25d7d4..f1d96f6658d 100644 --- a/turbo-ext/src/ConstantArrayType.cpp +++ b/turbo-ext/src/ConstantArrayType.cpp @@ -32,6 +32,8 @@ #include "TypeTraits.h" #include "generated/ConstantArrayType.h" +#include +#include #include namespace slots = ptdecl::ConstantArrayType::slot; @@ -788,6 +790,8 @@ static void ZEND_FASTCALL catSliceArray(INTERNAL_FUNCTION_PARAMETERS); static void ZEND_FASTCALL catIsIterableAtLeastOnce(INTERNAL_FUNCTION_PARAMETERS); static void ZEND_FASTCALL catGetArraySize(INTERNAL_FUNCTION_PARAMETERS); static void ZEND_FASTCALL catIsList(INTERNAL_FUNCTION_PARAMETERS); +static void ZEND_FASTCALL catIsKeyOrderKnown(INTERNAL_FUNCTION_PARAMETERS); +static void ZEND_FASTCALL catForgetKeyOrder(INTERNAL_FUNCTION_PARAMETERS); static void ZEND_FASTCALL catToBoolean(INTERNAL_FUNCTION_PARAMETERS); static void ZEND_FASTCALL catGetValuesArray(INTERNAL_FUNCTION_PARAMETERS); static void ZEND_FASTCALL catDescribe(INTERNAL_FUNCTION_PARAMETERS); @@ -835,7 +839,7 @@ class ConstantArrayType * ?TrinaryLogic $isList = null, ?array $unsealed = null); the NULL * arguments stand for the defaults, an IS_NULL $isList/$unsealed for * the twin's null; false = pending exception */ - [[nodiscard]] bool construct(zval *keyTypesArg, zval *valueTypesArg, zval *nextAutoIndexesArg, zval *optionalKeysArg, zval *isListArg, zval *unsealedArg) + [[nodiscard]] bool construct(zval *keyTypesArg, zval *valueTypesArg, zval *nextAutoIndexesArg, zval *optionalKeysArg, zval *isListArg, zval *unsealedArg, bool keyOrderKnown = true) { /* assert(count($keyTypes) === count($valueTypes)) — an * AssertionError when the engine evaluates assertions */ @@ -970,16 +974,19 @@ class ConstantArrayType } else { writeSlot(ref, slots::optionalKeys, zv::Val(zv::Arr::empty())); } + /* a list has its keys in the order it lists them */ + bool isListYes = trinaryOf(isList.raw()) == PT_TRI_YES; writeSlot(ref, slots::isList, std::move(isList)); writeSlot(ref, slots::unsealed, std::move(unsealed)); if (!unsealedDeclaration.isNull()) writeSlot(ref, slots::unsealedDeclaration, std::move(unsealedDeclaration)); + writeSlot(ref, slots::keyOrderKnown, zv::Val::boolean(keyOrderKnown || isListYes)); return true; } /* new self(...) — exactly the class, with the twin's typed parameters' * checks; the NULL/IS_NULL conventions of construct(); UNDEF = pending * exception */ - static zv::Val create(zval *keyTypes, zval *valueTypes, zval *nextAutoIndexes = NULL, zval *optionalKeys = NULL, zval *isList = NULL, zval *unsealed = NULL) + static zv::Val create(zval *keyTypes, zval *valueTypes, zval *nextAutoIndexes = NULL, zval *optionalKeys = NULL, zval *isList = NULL, zval *unsealed = NULL, bool keyOrderKnown = true) { if (UNEXPECTED(!checkArray(keyTypes, 1) || !checkArray(valueTypes, 2) || (nextAutoIndexes != NULL && !checkArray(nextAutoIndexes, 3)) @@ -990,7 +997,7 @@ class ConstantArrayType } zval object; if (UNEXPECTED(object_init_ex(&object, pt_ce_constant_array_type) != SUCCESS)) return zv::Val(); - if (UNEXPECTED(!ConstantArrayType(Z_OBJ(object)).construct(keyTypes, valueTypes, nextAutoIndexes, optionalKeys, isList, unsealed))) { + if (UNEXPECTED(!ConstantArrayType(Z_OBJ(object)).construct(keyTypes, valueTypes, nextAutoIndexes, optionalKeys, isList, unsealed, keyOrderKnown))) { zval_ptr_dtor(&object); return zv::Val(); } @@ -1103,7 +1110,106 @@ class ConstantArrayType { zv::Val kept = keepUnsealedDeclaration(unsealed); if (UNEXPECTED(kept.isUndef())) return zv::Val(); - return create(keyTypes, valueTypes, nextAutoIndexes, optionalKeys, isList, kept.raw()); + bool keyOrderKnown; + if (UNEXPECTED(!keyOrderKnownSlot(keyOrderKnown))) return zv::Val(); + return create(keyTypes, valueTypes, nextAutoIndexes, optionalKeys, isList, kept.raw(), keyOrderKnown); + } + + /* $this->keyOrderKnown || count($this->keyTypes) < 2 || $this->isList->yes(); + * false = pending exception */ + [[nodiscard]] bool isKeyOrderKnown(bool &out) const + { + bool keyOrderKnown; + if (UNEXPECTED(!keyOrderKnownSlot(keyOrderKnown))) return false; + if (keyOrderKnown) { + out = true; + return true; + } + zval *k = keyTypes(); + if (UNEXPECTED(k == NULL)) return false; + if (arrayCount(k) < 2) { + out = true; + return true; + } + zval *l = isListSlot(); + if (UNEXPECTED(l == NULL)) return false; + out = trinaryOf(l) == PT_TRI_YES; + return true; + } + + /* private hasKeyOrderToKeep(): $this->keyOrderKnown && count($this->keyTypes) > 1 + * && !$this->isList->yes(); false = pending exception */ + [[nodiscard]] bool hasKeyOrderToKeep(bool &out) const + { + bool keyOrderKnown; + if (UNEXPECTED(!keyOrderKnownSlot(keyOrderKnown))) return false; + if (!keyOrderKnown) { + out = false; + return true; + } + zval *k = keyTypes(); + if (UNEXPECTED(k == NULL)) return false; + if (arrayCount(k) < 2) { + out = false; + return true; + } + zval *l = isListSlot(); + if (UNEXPECTED(l == NULL)) return false; + out = trinaryOf(l) != PT_TRI_YES; + return true; + } + + /* forgetKeyOrder(): $this when it does not know its key order, else + * new self(...same..., $this->unsealedDeclaration ?? $this->unsealed, false) */ + zv::Val forgetKeyOrder() const + { + return withKeyOrderKnownSlot(false); + } + + /* private knowKeyOrder(): forgetKeyOrder()'s twin that sets the flag */ + zv::Val knowKeyOrder() const + { + return withKeyOrderKnownSlot(true); + } + + /* $this when its keyOrderKnown slot already is $flag, else new self(...same..., + * $this->unsealedDeclaration ?? $this->unsealed, $flag); UNDEF = pending exception */ + zv::Val withKeyOrderKnownSlot(bool flag) const + { + bool keyOrderKnown; + if (UNEXPECTED(!keyOrderKnownSlot(keyOrderKnown))) return zv::Val(); + if (keyOrderKnown == flag) return zv::Val::copyOf(zv::Ref(thisZv())); + zval *k = keyTypes(); + zval *v = k != NULL ? valueTypes() : NULL; + zval *n = v != NULL ? nextAutoIndexes() : NULL; + zval *o = n != NULL ? optionalKeys() : NULL; + zval *l = o != NULL ? isListSlot() : NULL; + zval *u = l != NULL ? unsealedSlot() : NULL; + if (UNEXPECTED(u == NULL)) return zv::Val(); + zval *declaration = unsealedDeclarationSlot(); + return create(k, v, n, o, l, Z_TYPE_P(declaration) == IS_ARRAY ? declaration : u, flag); + } + + /* $type->isKeyOrderKnown() of another shape: the native body for a + * native object, the method otherwise; false = pending exception */ + [[nodiscard]] static bool isKeyOrderKnownOf(zval *type, bool &out) + { + if (EXPECTED(pt_type_method_is(Z_OBJ_P(type), PT_LC("iskeyorderknown"), catIsKeyOrderKnown))) { + return ConstantArrayType(Z_OBJ_P(type)).isKeyOrderKnown(out); + } + zv::Val result = callType(Z_OBJ_P(type), PT_LC("iskeyorderknown"), 0, NULL); + if (UNEXPECTED(result.isUndef())) return false; + out = zend_is_true(result.raw()); + return true; + } + + /* $type->forgetKeyOrder() of another shape, as isKeyOrderKnownOf() */ + static zv::Val forgetKeyOrderOf(zval *type) + { + if (EXPECTED(pt_type_method_is(Z_OBJ_P(type), PT_LC("forgetkeyorder"), catForgetKeyOrder))) { + return ConstantArrayType(Z_OBJ_P(type)).forgetKeyOrder(); + } + return callType(Z_OBJ_P(type), PT_LC("forgetkeyorder"), 0, NULL); } /* [$this] */ @@ -1341,7 +1447,7 @@ class ConstantArrayType continue; } - zv::Val builder = builderCreateEmpty(); + zv::Val builder = builderCreateEmptyKeepingOrder(); if (UNEXPECTED(builder.isUndef())) return zv::Val(); if (UNEXPECTED(!builderCall0(builder.raw(), PT_LC("disablearraydegradation")))) return zv::Val(); for (zv::ArrayEntry entry : keys.arrRef()) { @@ -1437,12 +1543,7 @@ class ConstantArrayType zv::Val sortKeys() const { zval *k = keyTypes(); - zval *v = k != NULL ? valueTypes() : NULL; - zval *n = v != NULL ? nextAutoIndexes() : NULL; - zval *o = n != NULL ? optionalKeys() : NULL; - zval *l = o != NULL ? isListSlot() : NULL; - zval *u = l != NULL ? unsealedSlot() : NULL; - if (UNEXPECTED(u == NULL)) return zv::Val(); + if (UNEXPECTED(k == NULL)) return zv::Val(); /* $indices = array_keys($this->keyTypes); usort($indices, fn ($a, $b) => value($a) <=> value($b)) */ uint32_t count = zend_hash_num_elements(Z_ARRVAL_P(k)); @@ -1456,6 +1557,269 @@ class ConstantArrayType } if (UNEXPECTED(!usortIndicesByValue(indices, values))) return zv::Val(); + return reorderKeys(indices); + } + + /* sharesKeyOrderWith(): whether both shapes know their key order and + * list the keys they share in the same order; false = pending exception */ + [[nodiscard]] bool sharesKeyOrderWith(zend_object *other, bool &out) const + { + bool known; + if (UNEXPECTED(!thisIsKeyOrderKnown(known))) return false; + if (known) { + zval otherZv; + ZVAL_OBJ(&otherZv, other); + if (UNEXPECTED(!isKeyOrderKnownOf(&otherZv, known))) return false; + } + if (!known) { + out = false; + return true; + } + + zv::Val otherKeyIndexMap = ConstantArrayType(other).getKeyIndexMap(); + if (UNEXPECTED(otherKeyIndexMap.isUndef())) return false; + zval *k = keyTypes(); + if (UNEXPECTED(k == NULL)) return false; + zend_long lastIndex = -1; + for (zv::ArrayEntry entry : zv::ArrRef(k)) { + zv::Val keyValueZv = keyValue(entry.value().deref().raw()); + if (UNEXPECTED(keyValueZv.isUndef())) return false; + zval *otherIndex = mapFind(Z_ARRVAL_P(otherKeyIndexMap.raw()), keyValueZv.raw()); + if (otherIndex == NULL || Z_TYPE_P(otherIndex) != IS_LONG) continue; + if (Z_LVAL_P(otherIndex) < lastIndex) { + out = false; + return true; + } + lastIndex = Z_LVAL_P(otherIndex); + } + + out = true; + return true; + } + + /* inKeyOrderOf(): $this with its keys in the order of the first of the + * shapes that knows its key order and lists every key of this one, else + * $this->forgetKeyOrder(); UNDEF = pending exception */ + zv::Val inKeyOrderOf(zval *shapes, uint32_t count) const + { + bool keepOrder; + if (UNEXPECTED(!hasKeyOrderToKeep(keepOrder))) return zv::Val(); + if (!keepOrder) return zv::Val::copyOf(zv::Ref(thisZv())); + zval *k = keyTypes(); + if (UNEXPECTED(k == NULL)) return zv::Val(); + + for (uint32_t s = 0; s < count; s++) { + zval *shape = zv::Ref(&shapes[s]).deref().raw(); + bool known; + if (UNEXPECTED(!isKeyOrderKnownOf(shape, known))) return zv::Val(); + if (!known) continue; + + zv::Val shapeKeyIndexMap = ConstantArrayType(Z_OBJ_P(shape)).getKeyIndexMap(); + if (UNEXPECTED(shapeKeyIndexMap.isUndef())) return zv::Val(); + /* $indices[$shapeIndex] = $i; ksort($indices) */ + std::map byShapeIndex; + bool listsAll = true; + for (zv::ArrayEntry entry : zv::ArrRef(k)) { + zv::Val keyValueZv = keyValue(entry.value().deref().raw()); + if (UNEXPECTED(keyValueZv.isUndef())) return zv::Val(); + zval *shapeIndex = mapFind(Z_ARRVAL_P(shapeKeyIndexMap.raw()), keyValueZv.raw()); + if (shapeIndex == NULL || Z_TYPE_P(shapeIndex) != IS_LONG) { + listsAll = false; + break; + } + byShapeIndex[Z_LVAL_P(shapeIndex)] = (zend_long) entry.indexKey(); + } + if (!listsAll) continue; + + zv::Arr indices = zv::Arr::create((uint32_t) byShapeIndex.size()); + for (const auto &pair : byShapeIndex) { + indices.push(zv::Val::integer(pair.second)); + } + return reorderKeys(indices); + } + + return forgetKeyOrderOf(thisZv()); + } + + /* getKeyTypesInMergedOrderWith(): the keys of $this and $other in an + * order both keep - a key only one of them lists stays between the keys + * it is listed between there - or null when they do not share their key + * order; UNDEF = pending exception */ + zv::Val getKeyTypesInMergedOrderWith(zend_object *other) const + { + ConstantArrayType otherShape(other); + bool shares; + if (UNEXPECTED(!sharesKeyOrderWith(other, shares))) return zv::Val(); + if (!shares) return zv::Val::null(); + + zv::Val keyIndexMap = getKeyIndexMap(); + if (UNEXPECTED(keyIndexMap.isUndef())) return zv::Val(); + zv::Val otherKeyIndexMap = otherShape.getKeyIndexMap(); + if (UNEXPECTED(otherKeyIndexMap.isUndef())) return zv::Val(); + zval *k = keyTypes(); + zval *otherK = k != NULL ? otherShape.keyTypes() : NULL; + if (UNEXPECTED(otherK == NULL)) return zv::Val(); + zend_long count = (zend_long) arrayCount(k); + zend_long otherCount = (zend_long) arrayCount(otherK); + + zv::Arr merged = zv::Arr::create((uint32_t) (count + otherCount)); + auto listedIn = [&](zval *keyType, zval *map, bool &out) -> bool { + zv::Val keyValueZv = keyValue(keyType); + if (UNEXPECTED(keyValueZv.isUndef())) return false; + out = mapFind(Z_ARRVAL_P(map), keyValueZv.raw()) != NULL; + return true; + }; + zend_long i = 0; + zend_long j = 0; + while (i < count || j < otherCount) { + if (i < count) { + zval *keyType = arrayIndexObject(k, i, "keyTypes"); + if (UNEXPECTED(keyType == NULL)) return zv::Val(); + bool inOther; + if (UNEXPECTED(!listedIn(keyType, otherKeyIndexMap.raw(), inOther))) return zv::Val(); + if (!inOther) { + merged.push(zv::Ref(keyType)); + i++; + continue; + } + } + if (j < otherCount) { + zval *keyType = arrayIndexObject(otherK, j, "keyTypes"); + if (UNEXPECTED(keyType == NULL)) return zv::Val(); + bool inThis; + if (UNEXPECTED(!listedIn(keyType, keyIndexMap.raw(), inThis))) return zv::Val(); + if (!inThis) { + merged.push(zv::Ref(keyType)); + j++; + continue; + } + } + /* the next key of both is the same shared key */ + zval *keyType = arrayIndexObject(k, i, "keyTypes"); + if (UNEXPECTED(keyType == NULL)) return zv::Val(); + merged.push(zv::Ref(keyType)); + i++; + j++; + } + + return zv::Val(std::move(merged)); + } + + /* inMergedKeyOrderOf(): $this, holding the keys of $a and $b merged, + * with its keys in an order both keep - a key only one of them lists + * stays between the keys it is listed between there - else + * $this->forgetKeyOrder() when they do not share their key order; + * UNDEF = pending exception */ + zv::Val inMergedKeyOrderOf(zend_object *a, zend_object *b) const + { + ConstantArrayType aShape(a); + ConstantArrayType bShape(b); + bool shares; + if (UNEXPECTED(!aShape.sharesKeyOrderWith(b, shares))) return zv::Val(); + if (!shares) return forgetKeyOrderOf(thisZv()); + + zv::Val aKeyIndexMap = aShape.getKeyIndexMap(); + if (UNEXPECTED(aKeyIndexMap.isUndef())) return zv::Val(); + zv::Val bKeyIndexMap = bShape.getKeyIndexMap(); + if (UNEXPECTED(bKeyIndexMap.isUndef())) return zv::Val(); + zval *aK = aShape.keyTypes(); + zval *bK = aK != NULL ? bShape.keyTypes() : NULL; + zval *k = bK != NULL ? keyTypes() : NULL; + if (UNEXPECTED(k == NULL)) return zv::Val(); + zend_long aCount = (zend_long) arrayCount(aK); + zend_long bCount = (zend_long) arrayCount(bK); + + zv::Arr positions = zv::Arr::create((uint32_t) (aCount + bCount)); + zend_long position = 0; + auto place = [&](zval *keyType) -> bool { + zv::Val keyValueZv = keyValue(keyType); + if (UNEXPECTED(keyValueZv.isUndef())) return false; + zval positionZv; + ZVAL_LONG(&positionZv, position); + position++; + return mapSet(positions.table(), keyValueZv.raw(), &positionZv); + }; + auto listedIn = [&](zval *keyType, zval *keyIndexMap, bool &out) -> bool { + zv::Val keyValueZv = keyValue(keyType); + if (UNEXPECTED(keyValueZv.isUndef())) return false; + out = mapFind(Z_ARRVAL_P(keyIndexMap), keyValueZv.raw()) != NULL; + return true; + }; + zend_long i = 0; + zend_long j = 0; + while (i < aCount || j < bCount) { + if (i < aCount) { + zval *keyType = arrayIndexObject(aK, i, "keyTypes"); + if (UNEXPECTED(keyType == NULL)) return zv::Val(); + bool inB; + if (UNEXPECTED(!listedIn(keyType, bKeyIndexMap.raw(), inB))) return zv::Val(); + if (!inB) { + if (UNEXPECTED(!place(keyType))) return zv::Val(); + i++; + continue; + } + } + if (j < bCount) { + zval *keyType = arrayIndexObject(bK, j, "keyTypes"); + if (UNEXPECTED(keyType == NULL)) return zv::Val(); + bool inA; + if (UNEXPECTED(!listedIn(keyType, aKeyIndexMap.raw(), inA))) return zv::Val(); + if (!inA) { + if (UNEXPECTED(!place(keyType))) return zv::Val(); + j++; + continue; + } + } + /* the next key of both is the same shared key */ + zval *keyType = arrayIndexObject(aK, i, "keyTypes"); + if (UNEXPECTED(keyType == NULL || !place(keyType))) return zv::Val(); + i++; + j++; + } + + std::map byPosition; + for (zv::ArrayEntry entry : zv::ArrRef(k)) { + zv::Val keyValueZv = keyValue(entry.value().deref().raw()); + if (UNEXPECTED(keyValueZv.isUndef())) return zv::Val(); + zval *keyPosition = mapFind(positions.table(), keyValueZv.raw()); + if (UNEXPECTED(keyPosition == NULL || Z_TYPE_P(keyPosition) != IS_LONG)) { + zend_throw_error(NULL, "phpstan_turbo: a merged key is in neither shape"); + return zv::Val(); + } + byPosition[Z_LVAL_P(keyPosition)] = (zend_long) entry.indexKey(); + } + zv::Arr indices = zv::Arr::create((uint32_t) byPosition.size()); + for (const auto &pair : byPosition) { + indices.push(zv::Val::integer(pair.second)); + } + return reorderKeys(indices); + } + + /* private reorderKeys(): $this when the indices keep the order, else the + * keys, values and optional keys in the order of the indices; + * UNDEF = pending exception */ + zv::Val reorderKeys(zv::Arr &indices) const + { + zval *k = keyTypes(); + zval *v = k != NULL ? valueTypes() : NULL; + zval *n = v != NULL ? nextAutoIndexes() : NULL; + zval *o = n != NULL ? optionalKeys() : NULL; + zval *l = o != NULL ? isListSlot() : NULL; + zval *u = l != NULL ? unsealedSlot() : NULL; + if (UNEXPECTED(u == NULL)) return zv::Val(); + + uint32_t count = zend_hash_num_elements(Z_ARRVAL_P(k)); + bool unchanged = true; + zend_long expected = 0; + for (zv::ArrayEntry entry : indices.arrRef()) { + if (zv::Ref(entry.value().deref().raw()).asLong() != expected) { + unchanged = false; + break; + } + expected++; + } + if (unchanged && expected == (zend_long) count) return zv::Val::copyOf(zv::Ref(thisZv())); + zv::Arr newKeyTypes = zv::Arr::create(count); zv::Arr newValueTypes = zv::Arr::create(count); zv::ScratchTable indexMap(count); @@ -1505,6 +1869,36 @@ class ConstantArrayType return pt_type_call(Z_OBJ_P(type), PT_LC("isacceptedby"), 2, args); } + zv::Val orderConstantArrays = pt_type_call_array(Z_OBJ_P(type), PT_LC("getconstantarrays"), 0, NULL); + if (UNEXPECTED(orderConstantArrays.isUndef())) return zv::Val(); + if (arrayCount(orderConstantArrays.raw()) == 1) { + zval *constantArray = arrayIndexObject(orderConstantArrays.raw(), 0, "constantArrays"); + if (UNEXPECTED(constantArray == NULL)) return zv::Val(); + /* the shape that does not know its key order may hold its keys in + * another order than this one */ + bool keepOrder; + if (UNEXPECTED(!hasKeyOrderToKeep(keepOrder))) return zv::Val(); + bool otherKnown; + if (UNEXPECTED(!isKeyOrderKnownOf(constantArray, otherKnown))) return zv::Val(); + if (keepOrder && !otherKnown) { + zv::Val unordered = forgetKeyOrder(); + if (UNEXPECTED(unordered.isUndef())) return zv::Val(); + zv::Val accepted = ConstantArrayType(Z_OBJ_P(unordered.raw())).accepts(type, strictTypes); + if (UNEXPECTED(accepted.isUndef())) return zv::Val(); + zv::Val maybe = pt_type_accepts_result(PT_TRI_MAYBE); + if (UNEXPECTED(maybe.isUndef())) return zv::Val(); + return pt_type_result_and(std::move(accepted), maybe.raw()); + } + /* an array never has its keys in two orders */ + bool thisKnown; + if (UNEXPECTED(!thisIsKeyOrderKnown(thisKnown))) return zv::Val(); + if (thisKnown && otherKnown) { + bool shares; + if (UNEXPECTED(!sharesKeyOrderWith(Z_OBJ_P(constantArray), shares))) return zv::Val(); + if (!shares) return pt_type_accepts_result(PT_TRI_NO); + } + } + zend_long isUnsealed = thisIsUnsealed(); if (UNEXPECTED(isUnsealed < 0)) return zv::Val(); zval *k = keyTypes(); @@ -1907,6 +2301,16 @@ class ConstantArrayType } if (instanceof_function(Z_OBJCE_P(type), pt_ce_constant_array_type)) { + /* an array never has its keys in two orders */ + bool thisKnown, typeKnown = false; + if (UNEXPECTED(!thisIsKeyOrderKnown(thisKnown))) return zv::Val(); + if (thisKnown && UNEXPECTED(!isKeyOrderKnownOf(type, typeKnown))) return zv::Val(); + if (thisKnown && typeKnown) { + bool shares; + if (UNEXPECTED(!sharesKeyOrderWith(Z_OBJ_P(type), shares))) return zv::Val(); + if (!shares) return pt_type_is_super_type_of_result(PT_TRI_NO); + } + zend_long thisUnsealedness = thisIsUnsealed(); if (UNEXPECTED(thisUnsealedness < 0)) return zv::Val(); zend_long typeUnsealedness = pt_type_call_trinary(Z_OBJ_P(type), PT_LC("isunsealed"), 0, NULL); @@ -2136,6 +2540,20 @@ class ConstantArrayType } } + /* the shape that does not know its key order may hold its keys + * in another order than this one */ + bool keepOrder; + if (UNEXPECTED(!hasKeyOrderToKeep(keepOrder))) return zv::Val(); + if (keepOrder) { + bool otherKnown; + if (UNEXPECTED(!isKeyOrderKnownOf(type, otherKnown))) return zv::Val(); + if (!otherKnown) { + zv::Val maybe = pt_type_is_super_type_of_result(PT_TRI_MAYBE); + if (UNEXPECTED(maybe.isUndef())) return zv::Val(); + results.push(std::move(maybe)); + } + } + /* IsSuperTypeOfResult::createYes()->and(...$results) */ zv::Val yes = pt_type_is_super_type_of_result(PT_TRI_YES); if (UNEXPECTED(yes.isUndef())) return zv::Val(); @@ -2253,35 +2671,76 @@ class ConstantArrayType return true; } + bool keyOrderKnown, otherKeyOrderKnown; + if (UNEXPECTED(!thisIsKeyOrderKnown(keyOrderKnown))) return false; + if (UNEXPECTED(!isKeyOrderKnownOf(type, otherKeyOrderKnown))) return false; + if (keyOrderKnown != otherKeyOrderKnown) { + out = false; + return true; + } + zval *v = valueTypes(); zval *otherV = v != NULL ? slotOf(other, slots::valueTypes, "valueTypes") : NULL; if (UNEXPECTED(otherV == NULL)) return false; - for (zv::ArrayEntry entry : zv::ArrRef(k)) { - zend_long i = (zend_long) entry.indexKey(); - zval *keyType = entry.value().deref().raw(); - zval *valueType = arrayIndexObject(v, i, "valueTypes"); - zval *otherValueType = valueType != NULL ? arrayIndexObject(otherV, i, "valueTypes") : NULL; - if (UNEXPECTED(otherValueType == NULL)) return false; - if (!pt_call_type_equals(valueType, otherValueType)) { - if (UNEXPECTED(EG(exception))) return false; - out = false; - return true; + if (keyOrderKnown) { + for (zv::ArrayEntry entry : zv::ArrRef(k)) { + zend_long i = (zend_long) entry.indexKey(); + zval *keyType = entry.value().deref().raw(); + zval *valueType = arrayIndexObject(v, i, "valueTypes"); + zval *otherValueType = valueType != NULL ? arrayIndexObject(otherV, i, "valueTypes") : NULL; + if (UNEXPECTED(otherValueType == NULL)) return false; + if (!pt_call_type_equals(valueType, otherValueType)) { + if (UNEXPECTED(EG(exception))) return false; + out = false; + return true; + } + zval *otherKeyType = arrayIndexObject(otherK, i, "keyTypes"); + if (UNEXPECTED(otherKeyType == NULL)) return false; + if (!pt_call_type_equals(keyType, otherKeyType)) { + if (UNEXPECTED(EG(exception))) return false; + out = false; + return true; + } } - zval *otherKeyType = arrayIndexObject(otherK, i, "keyTypes"); - if (UNEXPECTED(otherKeyType == NULL)) return false; - if (!pt_call_type_equals(keyType, otherKeyType)) { - if (UNEXPECTED(EG(exception))) return false; + + zval *o = optionalKeys(); + zval *otherO = o != NULL ? slotOf(other, slots::optionalKeys, "optionalKeys") : NULL; + if (UNEXPECTED(otherO == NULL)) return false; + if (!zend_is_identical(o, otherO)) { out = false; return true; } - } - - zval *o = optionalKeys(); - zval *otherO = o != NULL ? slotOf(other, slots::optionalKeys, "optionalKeys") : NULL; - if (UNEXPECTED(otherO == NULL)) return false; - if (!zend_is_identical(o, otherO)) { - out = false; - return true; + } else { + /* shapes that do not know their key order are the same type + * whatever order they list their keys in */ + zv::Val otherKeyIndexMap = ConstantArrayType(other).getKeyIndexMap(); + if (UNEXPECTED(otherKeyIndexMap.isUndef())) return false; + for (zv::ArrayEntry entry : zv::ArrRef(k)) { + zend_long i = (zend_long) entry.indexKey(); + zv::Val keyValueZv = keyValue(entry.value().deref().raw()); + if (UNEXPECTED(keyValueZv.isUndef())) return false; + zval *jZv = mapFind(Z_ARRVAL_P(otherKeyIndexMap.raw()), keyValueZv.raw()); + if (jZv == NULL) { + out = false; + return true; + } + zend_long j = Z_LVAL_P(jZv); + zval *valueType = arrayIndexObject(v, i, "valueTypes"); + zval *otherValueType = valueType != NULL ? arrayIndexObject(otherV, j, "valueTypes") : NULL; + if (UNEXPECTED(otherValueType == NULL)) return false; + if (!pt_call_type_equals(valueType, otherValueType)) { + if (UNEXPECTED(EG(exception))) return false; + out = false; + return true; + } + bool optional, otherOptional; + if (UNEXPECTED(!thisIsOptionalKey(i, optional))) return false; + if (UNEXPECTED(!ConstantArrayType(other).isOptionalKey(j, otherOptional))) return false; + if (optional != otherOptional) { + out = false; + return true; + } + } } /* Both `unsealed === null` (legacy / pre-bleeding-edge, where @@ -3223,6 +3682,20 @@ class ConstantArrayType if (UNEXPECTED(unsealedness < 0)) return zv::Val(); if (unsealedness == PT_TRI_YES) return thisTraitChunkArray(lengthType, preserveKeys); + /* which of the values come in which chunk is not known */ + bool known; + if (UNEXPECTED(!thisIsKeyOrderKnown(known))) return zv::Val(); + if (!known) { + zend_long preserveKnown = trinaryOf(preserveKeys); + if (UNEXPECTED(preserveKnown < 0)) return zv::Val(); + if (preserveKnown != PT_TRI_YES) { + zv::Val values = thisGetValuesArray(); + if (UNEXPECTED(values.isUndef())) return zv::Val(); + zv::Args args{lengthType, preserveKeys}; + return callType(Z_OBJ_P(values.raw()), PT_LC("chunkarray"), 2, args); + } + } + zv::Val biggerOne = pt_integer_range_from_interval(NullableLong::of(1), NullableLong::null(), 0); if (UNEXPECTED(biggerOne.isUndef())) return zv::Val(); zv::Val finiteTypes = pt_type_call_array(Z_OBJ_P(lengthType), PT_LC("getfinitetypes"), 0, NULL); @@ -3242,7 +3715,7 @@ class ConstantArrayType if (isConstantInteger && UNEXPECTED(!pt_constant_integer_get_value(Z_OBJ_P(finiteType), length))) return zv::Val(); if (!isConstantInteger || length < 1) return thisTraitChunkArray(lengthType, preserveKeys); - zv::Val builder = builderCreateEmpty(); + zv::Val builder = builderCreateEmptyKeepingOrder(); if (UNEXPECTED(builder.isUndef())) return zv::Val(); zend_long keyTypesCount = arrayCount(k); @@ -3279,7 +3752,8 @@ class ConstantArrayType * UNDEF = pending exception */ zv::Val fillKeysArray(zval *valueType) const { - zv::Val builder = builderCreateEmpty(); + zv::Val builder = builderCreateEmptyKeepingOrder(); + if (UNEXPECTED(builder.isUndef())) return zv::Val(); zval *v = valueTypes(); if (UNEXPECTED(builder.isUndef() || v == NULL)) return zv::Val(); @@ -3340,7 +3814,8 @@ class ConstantArrayType * flipped; UNDEF = pending exception */ zv::Val flipArray() const { - zv::Val builder = builderCreateEmpty(); + zv::Val builder = builderCreateEmptyKeepingOrder(); + if (UNEXPECTED(builder.isUndef())) return zv::Val(); zval *k = keyTypes(); zval *v = k != NULL ? valueTypes() : NULL; if (UNEXPECTED(builder.isUndef() || v == NULL)) return zv::Val(); @@ -3391,7 +3866,8 @@ class ConstantArrayType * pending exception */ zv::Val intersectKeyArray(zval *otherArraysType) const { - zv::Val builder = builderCreateEmpty(); + zv::Val builder = builderCreateEmptyKeepingOrder(); + if (UNEXPECTED(builder.isUndef())) return zv::Val(); zval *k = keyTypes(); zval *v = k != NULL ? valueTypes() : NULL; if (UNEXPECTED(builder.isUndef() || v == NULL)) return zv::Val(); @@ -3432,13 +3908,40 @@ class ConstantArrayType return builderGetArray(builder.raw()); } - zv::Val popArray() const { return removeLastElements(1); } + /* the last element can be any of them when the key order is not known: + * $this->makeAllArrayKeysOptional(); else removeLastElements(1) */ + zv::Val popArray() const + { + bool known; + if (UNEXPECTED(!thisIsKeyOrderKnown(known))) return zv::Val(); + if (!known) return callType(self, PT_LC("makeallarraykeysoptional"), 0, NULL); + return removeLastElements(1); + } /* the keys in reverse order (integer keys renumbered unless preserved), * the unsealed pair kept; UNDEF = pending exception */ zv::Val reverseArray(zval *preserveKeys) const { - zv::Val builder = builderCreateEmpty(); + /* the integer keys are renumbered by positions that are not known */ + bool known; + if (UNEXPECTED(!thisIsKeyOrderKnown(known))) return zv::Val(); + if (!known) { + zend_long preserveKnown = trinaryOf(preserveKeys); + if (UNEXPECTED(preserveKnown < 0)) return zv::Val(); + if (preserveKnown != PT_TRI_YES) { + bool listsInteger; + if (UNEXPECTED(!listsIntegerKey(listsInteger))) return zv::Val(); + if (listsInteger) { + zv::Val walked = withoutPositionsOfKeys(); + if (UNEXPECTED(walked.isUndef())) return zv::Val(); + zv::Args args{preserveKeys}; + return callType(Z_OBJ_P(walked.raw()), PT_LC("reversearray"), 1, args); + } + } + } + + zv::Val builder = builderCreateEmptyKeepingOrder(); + if (UNEXPECTED(builder.isUndef())) return zv::Val(); zval *k = keyTypes(); zval *v = k != NULL ? valueTypes() : NULL; if (UNEXPECTED(builder.isUndef() || v == NULL)) return zv::Val(); @@ -3537,6 +4040,13 @@ class ConstantArrayType zval *keyType = arrayIndexObject(k, index, "keyTypes"); if (UNEXPECTED(keyType == NULL)) return zv::Val(); matches.push(zv::Ref(keyType)); + + /* the search stops at the first key that surely matches, unless the keys can come in any order */ + if (hasIdenticalValue) { + bool orderKnown; + if (UNEXPECTED(!isKeyOrderKnown(orderKnown))) return zv::Val(); + if (orderKnown) break; + } } /* Unsealed extras can host additional entries beyond the explicit @@ -3579,7 +4089,138 @@ class ConstantArrayType return constantBoolean(false); } - zv::Val shiftArray() const { return removeFirstElements(1, true); } + /* the first element can be any of them when the key order is not + * known, and the integer keys are renumbered by positions that are not + * known: all keys optional for string keys, else the shift of + * withoutPositionsOfKeys(); else removeFirstElements(1) */ + zv::Val shiftArray() const + { + bool known; + if (UNEXPECTED(!thisIsKeyOrderKnown(known))) return zv::Val(); + if (!known) { + bool listsInteger; + if (UNEXPECTED(!listsIntegerKey(listsInteger))) return zv::Val(); + if (!listsInteger) return callType(self, PT_LC("makeallarraykeysoptional"), 0, NULL); + zv::Val walked = withoutPositionsOfKeys(); + if (UNEXPECTED(walked.isUndef())) return zv::Val(); + return callType(Z_OBJ_P(walked.raw()), PT_LC("shiftarray"), 0, NULL); + } + return removeFirstElements(1, true); + } + + /* private listsIntegerKey(): whether one of the listed keys is an + * integer; false = pending exception */ + [[nodiscard]] bool listsIntegerKey(bool &out) const + { + zval *k = keyTypes(); + if (UNEXPECTED(k == NULL)) return false; + out = false; + for (zv::ArrayEntry entry : zv::ArrRef(k)) { + if (instanceof_function(Z_OBJCE_P(entry.value().deref().raw()), pt_ce_constant_integer_type)) { + out = true; + break; + } + } + return true; + } + + /* $this->getIterableKeyType()->isInteger(); -1 = pending exception */ + zend_long iterableKeyIsInteger() const + { + zv::Val keyType = thisGetIterableKeyType(); + if (UNEXPECTED(keyType.isUndef())) return -1; + return pt_type_op_trinary(Z_OBJ_P(keyType.raw()), PT_OP_IS_INTEGER, 0, NULL); + } + + /* private withoutPositionsOfKeys(): the list of the values when every + * key is an integer, the general array otherwise; UNDEF = pending + * exception */ + zv::Val withoutPositionsOfKeys() const + { + zend_long isInteger = iterableKeyIsInteger(); + if (UNEXPECTED(isInteger < 0)) return zv::Val(); + return isInteger == PT_TRI_YES ? thisGetValuesArray() : degradeToGeneralArray(); + } + + /* getValuesInKeyOrder(): $this when it knows its key order, else + * $this->getValuesArray(); UNDEF = pending exception */ + zv::Val getValuesInKeyOrder() const + { + bool known; + if (UNEXPECTED(!thisIsKeyOrderKnown(known))) return zv::Val(); + return known ? zv::Val::copyOf(zv::Ref(thisZv())) : thisGetValuesArray(); + } + + /* inRenumberingOrder(): $this when it knows its key order or has fewer + * than two integer keys; else each integer key holds the union of their + * values, the required ones listed first, the string keys unchanged; + * UNDEF = pending exception */ + zv::Val inRenumberingOrder() const + { + bool known; + if (UNEXPECTED(!thisIsKeyOrderKnown(known))) return zv::Val(); + if (known) return zv::Val::copyOf(zv::Ref(thisZv())); + + zval *k = keyTypes(); + zval *v = k != NULL ? valueTypes() : NULL; + zval *n = v != NULL ? nextAutoIndexes() : NULL; + zval *l = n != NULL ? isListSlot() : NULL; + zval *u = l != NULL ? unsealedSlot() : NULL; + if (UNEXPECTED(u == NULL)) return zv::Val(); + + zv::Arr integerValueTypes = zv::Arr::create(arrayCount(k)); + std::vector requiredIntegerKeys; + std::vector optionalIntegerKeys; + for (zv::ArrayEntry entry : zv::ArrRef(k)) { + zval *keyType = entry.value().deref().raw(); + if (!instanceof_function(Z_OBJCE_P(keyType), pt_ce_constant_integer_type)) continue; + zend_long i = (zend_long) entry.indexKey(); + zval *valueType = arrayIndexObject(v, i, "valueTypes"); + if (UNEXPECTED(valueType == NULL)) return zv::Val(); + integerValueTypes.push(zv::Ref(valueType)); + bool optional; + if (UNEXPECTED(!thisIsOptionalKey(i, optional))) return zv::Val(); + (optional ? optionalIntegerKeys : requiredIntegerKeys).push_back(keyType); + } + if (arrayCount(integerValueTypes.raw()) < 2) return zv::Val::copyOf(zv::Ref(thisZv())); + + zv::Val integerValueType = combinatorSpread(PT_LC("union"), Z_ARRVAL_P(integerValueTypes.raw())); + if (UNEXPECTED(integerValueType.isUndef())) return zv::Val(); + std::vector integerKeys = requiredIntegerKeys; + integerKeys.insert(integerKeys.end(), optionalIntegerKeys.begin(), optionalIntegerKeys.end()); + size_t nextIntegerKey = 0; + + uint32_t count = arrayCount(k); + zv::Arr newKeyTypes = zv::Arr::create(count); + zv::Arr newValueTypes = zv::Arr::create(count); + zv::Arr newOptionalKeys = zv::Arr::create(count); + for (zv::ArrayEntry entry : zv::ArrRef(k)) { + zval *keyType = entry.value().deref().raw(); + zend_long i = (zend_long) entry.indexKey(); + bool optional; + if (instanceof_function(Z_OBJCE_P(keyType), pt_ce_constant_integer_type)) { + keyType = integerKeys[nextIntegerKey]; + nextIntegerKey++; + newValueTypes.push(zv::Ref(integerValueType.raw())); + optional = nextIntegerKey > requiredIntegerKeys.size(); + } else { + zval *valueType = arrayIndexObject(v, i, "valueTypes"); + if (UNEXPECTED(valueType == NULL)) return zv::Val(); + newValueTypes.push(zv::Ref(valueType)); + if (UNEXPECTED(!thisIsOptionalKey(i, optional))) return zv::Val(); + } + newKeyTypes.push(zv::Ref(keyType)); + if (optional) { + newOptionalKeys.push(zv::Val::integer((zend_long) arrayCount(newKeyTypes.raw()) - 1)); + } + } + + zv::Val renumbered = thisRecreate(newKeyTypes.raw(), newValueTypes.raw(), n, newOptionalKeys.raw(), l, u); + if (UNEXPECTED(renumbered.isUndef())) return zv::Val(); + /* with only integer keys, each position holds any of the values, so the positions are all the order there is */ + if (arrayCount(integerValueTypes.raw()) != count) return renumbered; + return ConstantArrayType(Z_OBJ_P(renumbered.raw())).knowKeyOrder(); + } /* $this->getValuesArray()->degradeToGeneralArray() — the private method * on the values shape */ @@ -3605,6 +4246,23 @@ class ConstantArrayType zend_long keyTypesCount = arrayCount(k); if (keyTypesCount == 0) return zv::Val::copyOf(zv::Ref(thisZv())); + /* which of the keys come at the positions is not known, and the + * integer keys are renumbered by them */ + bool known; + if (UNEXPECTED(!thisIsKeyOrderKnown(known))) return zv::Val(); + if (!known) { + zend_long preserveKnown = trinaryOf(preserveKeys); + if (UNEXPECTED(preserveKnown < 0)) return zv::Val(); + if (preserveKnown == PT_TRI_YES) return callType(self, PT_LC("makeallarraykeysoptional"), 0, NULL); + bool listsInteger; + if (UNEXPECTED(!listsIntegerKey(listsInteger))) return zv::Val(); + if (!listsInteger) return callType(self, PT_LC("makeallarraykeysoptional"), 0, NULL); + zv::Val walked = withoutPositionsOfKeys(); + if (UNEXPECTED(walked.isUndef())) return zv::Val(); + zv::Args args{offsetTypeArg, lengthType, preserveKeys}; + return callType(Z_OBJ_P(walked.raw()), PT_LC("slicearray"), 3, args); + } + NullableLong offset = NullableLong::null(); if (instanceof_function(Z_OBJCE_P(offsetTypeArg), pt_ce_constant_integer_type)) { zend_long value; @@ -3701,7 +4359,8 @@ class ConstantArrayType return callType(Z_OBJ_P(shifted.raw()), PT_LC("slicearray"), 3, args); } - zv::Val builder = builderCreateEmpty(); + zv::Val builder = builderCreateEmptyKeepingOrder(); + if (UNEXPECTED(builder.isUndef())) return zv::Val(); zval *v = valueTypes(); if (UNEXPECTED(builder.isUndef() || v == NULL)) return zv::Val(); zend_long preserve = trinaryOf(preserveKeys); @@ -3775,6 +4434,16 @@ class ConstantArrayType zend_long keyTypesCount = arrayCount(k); if (keyTypesCount == 0) return zv::Val::copyOf(zv::Ref(thisZv())); + /* which of the keys come at the positions is not known */ + bool known; + if (UNEXPECTED(!thisIsKeyOrderKnown(known))) return zv::Val(); + if (!known) { + zv::Val general = degradeToGeneralArray(); + if (UNEXPECTED(general.isUndef())) return zv::Val(); + zv::Args args{offsetTypeArg, lengthType, replacementType}; + return callType(Z_OBJ_P(general.raw()), PT_LC("splicearray"), 3, args); + } + NullableLong offset = NullableLong::null(); if (instanceof_function(Z_OBJCE_P(offsetTypeArg), pt_ce_constant_integer_type)) { zend_long value; @@ -3847,7 +4516,7 @@ class ConstantArrayType zend_long removeKeysCount = 0; zend_long optionalKeysBeforeReplacement = 0; - zv::Val builder = builderCreateEmpty(); + zv::Val builder = builderCreateEmptyKeepingOrder(); if (UNEXPECTED(builder.isUndef())) return zv::Val(); for (zend_long i = 0;; i++) { bool isOptional; @@ -4034,7 +4703,7 @@ class ConstantArrayType if ((zend_long) builderData.arrRef().size() > limit) return intersectedWithNonEmpty(); - zv::Val builder = builderCreateEmpty(); + zv::Val builder = builderCreateEmptyKeepingOrder(); if (UNEXPECTED(builder.isUndef())) return zv::Val(); for (zv::ArrayEntry entry : builderData.arrRef()) { zval *triple = entry.value().deref().raw(); @@ -4142,10 +4811,20 @@ class ConstantArrayType /* the union of the leading keys up to the first required one, and the * unsealed key type (mixed substituted); UNDEF = pending exception */ - zv::Val getFirstIterableKeyType() const { return leadingUnion(true, true); } - zv::Val getLastIterableKeyType() const { return leadingUnion(true, false); } - zv::Val getFirstIterableValueType() const { return leadingUnion(false, true); } - zv::Val getLastIterableValueType() const { return leadingUnion(false, false); } + zv::Val getFirstIterableKeyType() const { return leadingUnionKnowingOrder(true, true); } + zv::Val getLastIterableKeyType() const { return leadingUnionKnowingOrder(true, false); } + zv::Val getFirstIterableValueType() const { return leadingUnionKnowingOrder(false, true); } + zv::Val getLastIterableValueType() const { return leadingUnionKnowingOrder(false, false); } + + /* if (!$this->isKeyOrderKnown()) return $this->getIterable(Key|Value)Type(); + * then the first or last keys or values up to the first required one */ + zv::Val leadingUnionKnowingOrder(bool keys, bool fromStart) const + { + bool known; + if (UNEXPECTED(!isKeyOrderKnown(known))) return zv::Val(); + if (!known) return keys ? getIterableKeyType() : getIterableValueType(); + return leadingUnion(keys, fromStart); + } static zend_long isConstantArray() { return PT_TRI_YES; } @@ -4252,7 +4931,8 @@ class ConstantArrayType * reindexing, the unsealed pair carried; UNDEF = pending exception */ zv::Val removeFirstElements(zend_long length, bool reindex) const { - zv::Val builder = builderCreateEmpty(); + zv::Val builder = builderCreateEmptyKeepingOrder(); + if (UNEXPECTED(builder.isUndef())) return zv::Val(); zval *k = keyTypes(); zval *v = k != NULL ? valueTypes() : NULL; if (UNEXPECTED(builder.isUndef() || v == NULL)) return zv::Val(); @@ -4526,6 +5206,31 @@ class ConstantArrayType resultUnsealed = pairOf(keyType.raw(), unsealedSourceTypeArg); } + /* any of the keys, and any of the extras, can come at any position */ + bool known; + if (UNEXPECTED(!thisIsKeyOrderKnown(known))) return zv::Val(); + if (!known) { + zv::Val valueType = combinatorSpread(PT_LC("union"), Z_ARRVAL_P(types)); + if (UNEXPECTED(valueType.isUndef())) return zv::Val(); + if (!resultUnsealed.isNull()) { + valueType = combinator2(PT_LC("union"), valueType.raw(), unsealedSourceTypeArg); + if (UNEXPECTED(valueType.isUndef())) return zv::Val(); + } + zend_long requiredCount = count - arrayCount(o); + zv::Arr keyTypesList = zv::Arr::create((uint32_t) count); + zv::Arr valueTypesList = zv::Arr::create((uint32_t) count); + zv::Arr optionalKeysList = zv::Arr::create((uint32_t) count); + for (zend_long i = 0; i < count; i++) { + zv::Val keyType = pt_type_new_constant_integer(i); + if (UNEXPECTED(keyType.isUndef())) return zv::Val(); + keyTypesList.push(std::move(keyType)); + valueTypesList.push(zv::Ref(valueType.raw())); + if (i < requiredCount) continue; + optionalKeysList.push(zv::Val::integer(i)); + } + return thisRecreate(keyTypesList.raw(), valueTypesList.raw(), autoIndexes.raw(), optionalKeysList.raw(), pt_trinary_singleton(PT_TRI_YES), resultUnsealed.raw()); + } + zend_long isListValue = trinaryOf(l); if (UNEXPECTED(isListValue < 0)) return zv::Val(); if (isListValue == PT_TRI_YES) { @@ -4637,12 +5342,15 @@ class ConstantArrayType zv::Val describe(zval *level) const { bool asList; - if (UNEXPECTED(!shouldBeDescribedAsAList(asList))) return zv::Val(); + if (UNEXPECTED(!shouldBeDescribedAsAList(asList, true))) return zv::Val(); const char *arrayName = asList ? "list" : "array"; + bool asListTypeOnly; + if (UNEXPECTED(!shouldBeDescribedAsAList(asListTypeOnly, false))) return zv::Val(); pt_verbosity_case which; if (UNEXPECTED(!pt_type_verbosity_case(level, which))) return zv::Val(); if (which == PT_VERBOSITY_TYPE_ONLY) { + arrayName = asListTypeOnly ? "list" : "array"; zend_long atLeastOnce = thisIsIterableAtLeastOnce(); if (UNEXPECTED(atLeastOnce < 0)) return zv::Val(); if (atLeastOnce == PT_TRI_NO) return zv::Val::string(arrayName, strlen(arrayName)); @@ -4678,9 +5386,10 @@ class ConstantArrayType return describeValueLevel(level, arrayName, which == PT_VERBOSITY_VALUE); } - /* private: a definite list with more than one optional key, or one - * that is not the last key; false = pending exception */ - [[nodiscard]] bool shouldBeDescribedAsAList(bool &out) const + /* private: a definite list with more than one optional key, with + * bleeding edge one with two or more keys, or one optional key that is + * not the last key; false = pending exception */ + [[nodiscard]] bool shouldBeDescribedAsAList(bool &out, bool namingKeys = true) const { zval *l = isListSlot(); zval *o = l != NULL ? optionalKeys() : NULL; @@ -4701,8 +5410,17 @@ class ConstantArrayType return true; } zval *k = keyTypes(); - zval *first = k != NULL ? zend_hash_index_find(Z_ARRVAL_P(o), 0) : NULL; if (UNEXPECTED(k == NULL)) return false; + /* with bleeding edge, a shape that lists two or more keys is not a list */ + if (namingKeys && arrayCount(k) > 1) { + bool bleedingEdge; + if (UNEXPECTED(!isBleedingEdge(bleedingEdge))) return false; + if (bleedingEdge) { + out = true; + return true; + } + } + zval *first = zend_hash_index_find(Z_ARRVAL_P(o), 0); /* $this->optionalKeys[0] !== count($this->keyTypes) - 1 */ out = first == NULL || Z_TYPE_P(first) != IS_LONG || Z_LVAL_P(first) != arrayCount(k) - 1; return true; @@ -5431,8 +6149,12 @@ class ConstantArrayType if (UNEXPECTED(inferred < 0)) return zv::Val(); isListValue = naiveIsList | inferred; } + /* the keys do not come in one known order: a list in one order may not be one in the other */ + bool sharesKeyOrder; + if (UNEXPECTED(!sharesKeyOrderWith(other, sharesKeyOrder))) return zv::Val(); + if (!sharesKeyOrder) isListValue = thisIsListValue == otherIsListValue ? thisIsListValue : PT_TRI_MAYBE; - return thisRecreate(keyTypesNew.raw(), valueTypesNew.raw(), nextAutoIndexesNew.raw(), optionalKeysUnique.raw(), pt_trinary_singleton(isListValue), resultUnsealed.raw()); + return inMergedKeyOrder(otherArray, sharesKeyOrder, thisRecreate(keyTypesNew.raw(), valueTypesNew.raw(), nextAutoIndexesNew.raw(), optionalKeysUnique.raw(), pt_trinary_singleton(isListValue), resultUnsealed.raw())); } /* private: our keys with the other's values unioned in (optional where @@ -5507,8 +6229,11 @@ class ConstantArrayType if (UNEXPECTED(inferred < 0)) return zv::Val(); isListValue = naiveIsList | inferred; } + bool sharesKeyOrder; + if (UNEXPECTED(!sharesKeyOrderWith(other, sharesKeyOrder))) return zv::Val(); + if (!sharesKeyOrder) isListValue = thisIsListValue == otherIsListValue ? thisIsListValue : PT_TRI_MAYBE; - return thisRecreate(k, valueTypesNew.raw(), nextAutoIndexesNew.raw(), optionalKeysUnique.raw(), pt_trinary_singleton(isListValue), u); + return inMergedKeyOrder(otherArray, sharesKeyOrder, thisRecreate(k, valueTypesNew.raw(), nextAutoIndexesNew.raw(), optionalKeysUnique.raw(), pt_trinary_singleton(isListValue), u)); } /* private, memoized in $keyIndexMap: key value → index; UNDEF = @@ -5748,6 +6473,26 @@ class ConstantArrayType if (isListValue == PT_TRI_NO) return neverType(); + /* a list has its keys in ascending order */ + bool known; + if (UNEXPECTED(!isKeyOrderKnown(known))) return zv::Val(); + if (!known) { + zv::Val sorted = sortKeys(); + if (UNEXPECTED(sorted.isUndef())) return zv::Val(); + ConstantArrayType sortedShape(Z_OBJ_P(sorted.raw())); + zval *sk = sortedShape.keyTypes(); + zval *sv = sk != NULL ? sortedShape.valueTypes() : NULL; + zval *sn = sv != NULL ? sortedShape.nextAutoIndexes() : NULL; + zval *so = sn != NULL ? sortedShape.optionalKeys() : NULL; + zval *sl = so != NULL ? sortedShape.isListSlot() : NULL; + zval *su = sl != NULL ? sortedShape.unsealedSlot() : NULL; + if (UNEXPECTED(su == NULL)) return zv::Val(); + zval *declaration = sortedShape.unsealedDeclarationSlot(); + zv::Val ordered = create(sk, sv, sn, so, sl, Z_TYPE_P(declaration) == IS_ARRAY ? declaration : su, true); + if (UNEXPECTED(ordered.isUndef())) return zv::Val(); + return ConstantArrayType(Z_OBJ_P(ordered.raw())).makeList(); + } + /* isList is Maybe. In a sealed shape a key past a gap in the 0..n * sequence (or any non-integer key) can never appear in a list, so * keep only the contiguous 0..m prefix. Unsealed extras may fill the @@ -5774,7 +6519,7 @@ class ConstantArrayType } if ((zend_long) keptPositions.arrRef().size() < arrayCount(k)) { - zv::Val builder = builderCreateEmpty(); + zv::Val builder = builderCreateEmptyKeepingOrder(); if (UNEXPECTED(builder.isUndef())) return zv::Val(); for (zv::ArrayEntry entry : keptPositions.arrRef()) { zend_long position = zv::Ref(entry.value().deref().raw()).asLong(); @@ -5870,7 +6615,8 @@ class ConstantArrayType * re-attached for a list; UNDEF = pending exception */ zv::Val changeKeyCaseArray(NullableLong caseArg) const { - zv::Val builder = builderCreateEmpty(); + zv::Val builder = builderCreateEmptyKeepingOrder(); + if (UNEXPECTED(builder.isUndef())) return zv::Val(); zval *k = keyTypes(); zval *v = k != NULL ? valueTypes() : NULL; zval *u = v != NULL ? unsealedSlot() : NULL; @@ -5923,7 +6669,8 @@ class ConstantArrayType } return zv::Val(); } - zv::Val builder = builderCreateEmpty(); + zv::Val builder = builderCreateEmptyKeepingOrder(); + if (UNEXPECTED(builder.isUndef())) return zv::Val(); zval *k = keyTypes(); zval *v = k != NULL ? valueTypes() : NULL; zval *u = v != NULL ? unsealedSlot() : NULL; @@ -6306,7 +7053,7 @@ class ConstantArrayType if (count > limit) return zv::Val(zv::Arr::empty()); } - zv::Val firstBuilder = builderCreateEmpty(); + zv::Val firstBuilder = builderCreateEmptyKeepingOrder(); if (UNEXPECTED(firstBuilder.isUndef())) return zv::Val(); zv::Arr partials = zv::Arr::create(1); partials.push(std::move(firstBuilder)); @@ -6499,6 +7246,42 @@ class ConstantArrayType zval *unsealedSlot() const { return slotOf(self, slots::unsealed, "unsealed", true); } /* $this->unsealedDeclaration: a defaulted ?array slot, never uninitialized */ zval *unsealedDeclarationSlot() const { return OBJ_PROP_NUM(self, slots::unsealedDeclaration); } + /* mergeWith()'s and legacyMergeWith()'s end: the merged shape knows + * its key order only when both shapes it merges know the same one - + * !$sharesKeyOrder && $merged instanceof TemplateType ? $merged : + * $merged->inMergedKeyOrderOf($this, $otherArray) */ + zv::Val inMergedKeyOrder(zval *otherArray, bool sharesKeyOrder, zv::Val merged) const + { + if (UNEXPECTED(merged.isUndef())) return zv::Val(); + if (!sharesKeyOrder) { + bool isTemplate; + if (UNEXPECTED(!pt_type_instanceof(merged.raw(), PT_CLASS_TEMPLATE_TYPE, isTemplate))) return zv::Val(); + if (isTemplate) return merged; + } + return ConstantArrayType(Z_OBJ_P(merged.raw())).inMergedKeyOrderOf(self, Z_OBJ_P(otherArray)); + } + + /* ConstantArrayTypeBuilder::createEmpty(), then ->makeKeyOrderKnown() + * when $this->keyOrderKnown - the builders the twin rebuilds this + * shape with; UNDEF = pending exception */ + zv::Val builderCreateEmptyKeepingOrder() const + { + zv::Val builder = builderCreateEmpty(); + if (UNEXPECTED(builder.isUndef())) return zv::Val(); + bool keyOrderKnown; + if (UNEXPECTED(!keyOrderKnownSlot(keyOrderKnown))) return zv::Val(); + if (keyOrderKnown && UNEXPECTED(!pt_constant_array_type_builder_make_key_order_known(builder.raw()))) return zv::Val(); + return builder; + } + + /* $this->keyOrderKnown; false with an Error pending when uninitialized */ + [[nodiscard]] bool keyOrderKnownSlot(bool &out) const + { + zval *slot = slotOf(self, slots::keyOrderKnown, "keyOrderKnown"); + if (UNEXPECTED(slot == NULL)) return false; + out = Z_TYPE_P(slot) != IS_FALSE; + return true; + } /* the constructor's slot initialization: the value in, IS_PROP_UNINIT * cleared */ @@ -6620,6 +7403,12 @@ class ConstantArrayType return pt_type_op_trinary(self, PT_OP_IS_ITERABLE_AT_LEAST_ONCE, 0, NULL); } + /* $this->isKeyOrderKnown() through the object's class; false = pending exception */ + [[nodiscard]] bool thisIsKeyOrderKnown(bool &out) const + { + return isKeyOrderKnownOf(thisZv(), out); + } + zend_long thisIsList() const { if (EXPECTED(ownMethod(PT_LC("islist"), catIsList))) { @@ -7625,7 +8414,22 @@ class ConstantArrayType } } - /* sprintf('%s{%s%s}', $arrayName, implode(', ', $exportValuesOnly ? $values : $items), $append) */ + /* sprintf('%s{%s%s}%s', $arrayName, implode(', ', $exportValuesOnly ? $values : $items), $append, + * $level->isCache() && !$this->isKeyOrderKnown() ? '(unordered)' : '') */ + pt_verbosity_case levelCase; + if (UNEXPECTED(!pt_type_verbosity_case(level, levelCase))) { + smart_str_free(&append); + return zv::Val(); + } + bool unorderedMarker = false; + if (levelCase == PT_VERBOSITY_CACHE) { + bool known; + if (UNEXPECTED(!thisIsKeyOrderKnown(known))) { + smart_str_free(&append); + return zv::Val(); + } + unorderedMarker = !known; + } smart_str result = {NULL, 0}; smart_str_appends(&result, arrayName); smart_str_appendc(&result, '{'); @@ -7640,6 +8444,7 @@ class ConstantArrayType smart_str_append_smart_str(&result, &append); smart_str_free(&append); smart_str_appendc(&result, '}'); + if (unorderedMarker) smart_str_appendl(&result, "(unordered)", sizeof("(unordered)") - 1); smart_str_0(&result); return zv::Val::adoptString(result.s); } @@ -7659,9 +8464,9 @@ zv::Val pt_constant_array_type_keep_unsealed_declaration(zend_object *object, zv return ConstantArrayType(object).keepUnsealedDeclaration(unsealed); } -bool pt_constant_array_type_new(zval *out, zval *keyTypes, zval *valueTypes, zval *nextAutoIndexes, zval *optionalKeys, zval *isList, zval *unsealed) +bool pt_constant_array_type_new(zval *out, zval *keyTypes, zval *valueTypes, zval *nextAutoIndexes, zval *optionalKeys, zval *isList, zval *unsealed, bool keyOrderKnown) { - return pt_val_into(ConstantArrayType::create(keyTypes, valueTypes, nextAutoIndexes, optionalKeys, isList, unsealed), out); + return pt_val_into(ConstantArrayType::create(keyTypes, valueTypes, nextAutoIndexes, optionalKeys, isList, unsealed, keyOrderKnown), out); } bool pt_constant_array_type_is_valid_identifier(zend_string *value, bool &out) @@ -7822,6 +8627,17 @@ static void ZEND_FASTCALL catIsList(INTERNAL_FUNCTION_PARAMETERS) pt_cat_no_args(INTERNAL_FUNCTION_PARAM_PASSTHRU, &ConstantArrayType::isList); } +static void ZEND_FASTCALL catIsKeyOrderKnown(INTERNAL_FUNCTION_PARAMETERS) +{ + ZEND_PARSE_PARAMETERS_NONE(); + PT_RETURN_BOOL_OR_THROW(PT_THIS.isKeyOrderKnown(pt_out__)); +} + +static void ZEND_FASTCALL catForgetKeyOrder(INTERNAL_FUNCTION_PARAMETERS) +{ + pt_cat_no_args(INTERNAL_FUNCTION_PARAM_PASSTHRU, &ConstantArrayType::forgetKeyOrder); +} + static void ZEND_FASTCALL catToBoolean(INTERNAL_FUNCTION_PARAMETERS) { pt_cat_no_args(INTERNAL_FUNCTION_PARAM_PASSTHRU, &ConstantArrayType::toBoolean); @@ -7872,6 +8688,7 @@ PT_MINIT_REGISTRATION(pt_register_constant_array_type) cls.privateTypedProperty("valueTypes", MAY_BE_ARRAY); cls.privateTypedProperty("nextAutoIndexes", MAY_BE_ARRAY); cls.privateTypedProperty("optionalKeys", MAY_BE_ARRAY); + cls.privateTypedProperty("keyOrderKnown", MAY_BE_BOOL); cls.privateTypedArrayPropertyDefaultEmpty("normalizedValueTypes"); cls.privateTypedArrayPropertyDefaultEmpty("generalizedTypes"); cls.privateClassConstantLong("DESCRIBE_LIMIT", PT_CAT_DESCRIBE_LIMIT); @@ -7880,11 +8697,25 @@ PT_MINIT_REGISTRATION(pt_register_constant_array_type) cls.method(sigs::__construct, [](INTERNAL_FUNCTION_PARAMETERS) { zval *keyTypes, *valueTypes, *nextAutoIndexes = NULL, *optionalKeys = NULL, *isList = NULL, *unsealed = NULL; - if (!zp::parse, zp::Opt, zp::Opt, zp::Opt>(execute_data, keyTypes, valueTypes, nextAutoIndexes, optionalKeys, isList, unsealed)) RETURN_THROWS(); + bool keyOrderKnown = true; + /* seven parameters: the raw macros, zp::parse stops at six */ + ZEND_PARSE_PARAMETERS_START(2, 7) + Z_PARAM_ARRAY(keyTypes) + Z_PARAM_ARRAY(valueTypes) + Z_PARAM_OPTIONAL + Z_PARAM_ARRAY(nextAutoIndexes) + Z_PARAM_ARRAY(optionalKeys) + Z_PARAM_OBJECT_OR_NULL(isList) + Z_PARAM_ARRAY_OR_NULL(unsealed) + Z_PARAM_BOOL(keyOrderKnown) + ZEND_PARSE_PARAMETERS_END(); if (isList != NULL && UNEXPECTED(!ConstantArrayType::checkNullableTrinary(isList, 5))) RETURN_THROWS(); - if (UNEXPECTED(!PT_THIS.construct(keyTypes, valueTypes, nextAutoIndexes, optionalKeys, isList, unsealed))) RETURN_THROWS(); + if (UNEXPECTED(!PT_THIS.construct(keyTypes, valueTypes, nextAutoIndexes, optionalKeys, isList, unsealed, keyOrderKnown))) RETURN_THROWS(); }); + cls.method(sigs::isKeyOrderKnown, catIsKeyOrderKnown); + cls.method(sigs::forgetKeyOrder, catForgetKeyOrder); + cls.method(sigs::isSealed, [](INTERNAL_FUNCTION_PARAMETERS) { pt_cat_no_args(INTERNAL_FUNCTION_PARAM_PASSTHRU, &ConstantArrayType::isSealed); }); @@ -7954,6 +8785,54 @@ PT_MINIT_REGISTRATION(pt_register_constant_array_type) pt_cat_no_args(INTERNAL_FUNCTION_PARAM_PASSTHRU, &ConstantArrayType::sortKeys); }); + cls.method(sigs::getValuesInKeyOrder, [](INTERNAL_FUNCTION_PARAMETERS) { + pt_cat_no_args(INTERNAL_FUNCTION_PARAM_PASSTHRU, &ConstantArrayType::getValuesInKeyOrder); + }); + + cls.method(sigs::inRenumberingOrder, [](INTERNAL_FUNCTION_PARAMETERS) { + pt_cat_no_args(INTERNAL_FUNCTION_PARAM_PASSTHRU, &ConstantArrayType::inRenumberingOrder); + }); + + cls.method(sigs::sharesKeyOrderWith, [](INTERNAL_FUNCTION_PARAMETERS) { + zval *other; + ZEND_PARSE_PARAMETERS_START(1, 1) + Z_PARAM_OBJECT_OF_CLASS(other, pt_ce_constant_array_type) + ZEND_PARSE_PARAMETERS_END(); + PT_RETURN_BOOL_OR_THROW(PT_THIS.sharesKeyOrderWith(Z_OBJ_P(other), pt_out__)); + }); + + cls.method(sigs::inKeyOrderOf, [](INTERNAL_FUNCTION_PARAMETERS) { + zval *shapes = NULL; + uint32_t count = 0; + ZEND_PARSE_PARAMETERS_START(0, -1) + Z_PARAM_VARIADIC('*', shapes, count) + ZEND_PARSE_PARAMETERS_END(); + for (uint32_t i = 0; i < count; i++) { + if (UNEXPECTED(!zv::Ref(&shapes[i]).deref().instanceOf(pt_ce_constant_array_type))) { + zend_argument_type_error(i + 1, "must be of type %s", ZSTR_VAL(pt_ce_constant_array_type->name)); + RETURN_THROWS(); + } + } + PT_RETURN_VAL(PT_THIS.inKeyOrderOf(shapes, count)); + }); + + cls.method(sigs::getKeyTypesInMergedOrderWith, [](INTERNAL_FUNCTION_PARAMETERS) { + zval *other; + ZEND_PARSE_PARAMETERS_START(1, 1) + Z_PARAM_OBJECT_OF_CLASS(other, pt_ce_constant_array_type) + ZEND_PARSE_PARAMETERS_END(); + PT_RETURN_VAL(PT_THIS.getKeyTypesInMergedOrderWith(Z_OBJ_P(other))); + }); + + cls.method(sigs::inMergedKeyOrderOf, [](INTERNAL_FUNCTION_PARAMETERS) { + zval *a, *b; + ZEND_PARSE_PARAMETERS_START(2, 2) + Z_PARAM_OBJECT_OF_CLASS(a, pt_ce_constant_array_type) + Z_PARAM_OBJECT_OF_CLASS(b, pt_ce_constant_array_type) + ZEND_PARSE_PARAMETERS_END(); + PT_RETURN_VAL(PT_THIS.inMergedKeyOrderOf(Z_OBJ_P(a), Z_OBJ_P(b))); + }); + cls.method<&ConstantArrayType::accepts, zp::Obj, zp::Bool>(sigs::accepts); cls.op(PT_OP_ACCEPTS, PT_OP_LAMBDA { return ConstantArrayType(self).accepts(argv, (Z_TYPE(argv[1]) == IS_TRUE)); }); diff --git a/turbo-ext/src/ConstantArrayTypeBuilder.cpp b/turbo-ext/src/ConstantArrayTypeBuilder.cpp index 6e50dbc55f8..20c58b7f6aa 100644 --- a/turbo-ext/src/ConstantArrayTypeBuilder.cpp +++ b/turbo-ext/src/ConstantArrayTypeBuilder.cpp @@ -39,6 +39,9 @@ namespace catSlots = ptdecl::ConstantArrayType::slot; namespace phpstanturbo { +/* the sort values forgetListKeyOrder() compares its indices by */ +static HashTable *pt_catb_sort_values = NULL; + /* Mirrors PHPStan\Type\Constant\ConstantArrayTypeBuilder. State lives in * the PHP object's slots. */ class ConstantArrayTypeBuilder @@ -119,6 +122,11 @@ class ConstantArrayTypeBuilder } zv::ObjRef(Z_OBJ(object)).propAtWrite(slots::isNonEmpty, std::move(isNonEmpty)); + /* $builder->keyOrderKnown = $startArrayType->isKeyOrderKnown() */ + zv::Val keyOrderKnown = pt_type_call(array, PT_LC("iskeyorderknown"), 0, NULL); + if (UNEXPECTED(keyOrderKnown.isUndef())) return zv::Val(); + zv::ObjRef(Z_OBJ(object)).propAtWrite(slots::keyOrderKnown, zv::Val::boolean(zend_is_true(keyOrderKnown.raw()))); + /* an array built on keeps the unsealed key that declares a template * for as long as its extras stay as they are */ zend_long startUnsealed = pt_type_op_trinary(array, PT_OP_IS_UNSEALED, 0, NULL); @@ -207,6 +215,73 @@ class ConstantArrayTypeBuilder return setUnsealed(merged.raw()); } + /* forgetListKeyOrder(): the list-ness a fresh builder gives the keys in + * ascending order (integers first), only maybe with two or more keys; + * false = pending exception */ + [[nodiscard]] bool forgetListKeyOrder() + { + /* a builder that degrades has keys without a value to sort them by */ + if (flag(slots::degradeToGeneralArray)) { + andIsListMaybe(); + return !EG(exception); + } + + zval *keyTypes = arraySlot(slots::keyTypes, "keyTypes"); + zval *valueTypes = keyTypes != NULL ? arraySlot(slots::valueTypes, "valueTypes") : NULL; + if (UNEXPECTED(valueTypes == NULL)) return false; + + /* $indices = array_keys($this->keyTypes); usort($indices, fn ($a, $b) => [!is_int(value($a)), value($a)] <=> [!is_int(value($b)), value($b)]) */ + uint32_t count = zend_hash_num_elements(Z_ARRVAL_P(keyTypes)); + zv::Arr sortValues = zv::Arr::create(count); + zv::Arr indices = zv::Arr::create(count); + for (zv::ArrayEntry entry : zv::ArrRef(keyTypes)) { + zv::Val value = constantValue(entry.value().deref().raw()); + if (UNEXPECTED(value.isUndef())) return false; + zv::Arr pair = zv::Arr::create(2); + pair.push(zv::Val::boolean(Z_TYPE_P(value.raw()) != IS_LONG)); + pair.push(std::move(value)); + sortValues.push(zv::Val(std::move(pair))); + indices.push(zv::Val::integer((zend_long) entry.indexKey())); + } + indices.separate(); + HashTable *previous = pt_catb_sort_values; + pt_catb_sort_values = sortValues.table(); + zend_hash_sort_ex(indices.table(), zend_sort, compareIndicesBySortValue, 1); + pt_catb_sort_values = previous; + if (UNEXPECTED(EG(exception))) return false; + + zv::Val sorted = createEmpty(); + if (UNEXPECTED(sorted.isUndef())) return false; + ConstantArrayTypeBuilder sortedBuilder(Z_OBJ_P(sorted.raw())); + for (zv::ArrayEntry entry : indices.arrRef()) { + zend_long i = zv::Ref(entry.value().deref().raw()).asLong(); + zval *keyType = zend_hash_index_find(Z_ARRVAL_P(keyTypes), (zend_ulong) i); + zval *valueType = zend_hash_index_find(Z_ARRVAL_P(valueTypes), (zend_ulong) i); + zval *optionalKeys = arraySlot(slots::optionalKeys, "optionalKeys"); + if (UNEXPECTED(keyType == NULL || valueType == NULL || optionalKeys == NULL)) return false; + if (UNEXPECTED(!sortedBuilder.setOffsetValueType(keyType, valueType, inArrayLong(Z_ARRVAL_P(optionalKeys), i)))) return false; + } + + zend_long sortedIsList = sortedBuilder.trinary(slots::isList, "isList"); + if (UNEXPECTED(sortedIsList < 0)) return false; + /* a single key has no order to forget */ + setTrinary(slots::isList, count < 2 ? sortedIsList : (sortedIsList & PT_TRI_MAYBE)); + return true; + } + + /* usort()'s comparison of two indices by their sort values, with its + * stable fallback to the original order */ + static int compareIndicesBySortValue(Bucket *a, Bucket *b) + { + zval *va = zend_hash_index_find(pt_catb_sort_values, (zend_ulong) Z_LVAL(a->val)); + zval *vb = zend_hash_index_find(pt_catb_sort_values, (zend_ulong) Z_LVAL(b->val)); + int result = va != NULL && vb != NULL ? zend_compare(va, vb) : 0; + if (result == 0) { + return Z_EXTRA(a->val) > Z_EXTRA(b->val) ? 1 : (Z_EXTRA(a->val) < Z_EXTRA(b->val) ? -1 : 0); + } + return result > 0 ? 1 : -1; + } + /* the twin's setOffsetValueType(?Type $offsetType, Type $valueType, * bool $optional); $offsetTypeArg NULL or IS_NULL for null; false = * pending exception */ @@ -393,13 +468,13 @@ class ConstantArrayTypeBuilder if (UNEXPECTED(valueTypes == NULL)) return zv::Val(); zval *optionalKeys = arraySlot(slots::optionalKeys, "optionalKeys"); if (UNEXPECTED(optionalKeys == NULL)) return zv::Val(); - zval *isList = objectSlot(slots::isList, "isList"); + zval *isList = listness(); if (UNEXPECTED(isList == NULL)) return zv::Val(); if (!flag(slots::degradeToGeneralArray)) { zval *nextAutoIndexes = arraySlot(slots::nextAutoIndexes, "nextAutoIndexes"); if (UNEXPECTED(nextAutoIndexes == NULL)) return zv::Val(); zval raw; - if (UNEXPECTED(!pt_constant_array_type_new(&raw, keyTypes, valueTypes, nextAutoIndexes, optionalKeys, isList, unsealedForArray()))) return zv::Val(); + if (UNEXPECTED(!pt_constant_array_type_new(&raw, keyTypes, valueTypes, nextAutoIndexes, optionalKeys, isList, unsealedForArray(), flag(slots::keyOrderKnown)))) return zv::Val(); zv::Val array = zv::Val::adopt(raw); if (isNonEmpty == PT_TRI_YES) { zend_long atLeastOnce = pt_type_op_trinary(Z_OBJ_P(array.raw()), PT_OP_IS_ITERABLE_AT_LEAST_ONCE, 0, NULL); @@ -468,14 +543,35 @@ class ConstantArrayTypeBuilder return pt_intersection_of(std::move(types)); } - /* $this->isList->yes(); -1 = pending exception */ + /* $this->getListness()->yes(); -1 = pending exception */ [[nodiscard]] zend_long isList() { - zend_long value = trinary(slots::isList, "isList"); + zval *listnessObject = listness(); + if (UNEXPECTED(listnessObject == NULL)) return -1; + zend_long value = pt_type_trinary_value(listnessObject); if (UNEXPECTED(value < 0)) return -1; return value == PT_TRI_YES ? 1 : 0; } + /* getListness(): keys set in no known order do not say they come as a + * list, only that they can - $this->isList->and(TrinaryLogic::createMaybe()) + * under bleeding edge; a borrowed TrinaryLogic, NULL = pending exception */ + zval *listness() + { + zval *isList = objectSlot(slots::isList, "isList"); + if (UNEXPECTED(isList == NULL)) return NULL; + if (flag(slots::keyOrderKnown)) return isList; + zval *keyTypes = arraySlot(slots::keyTypes, "keyTypes"); + if (UNEXPECTED(keyTypes == NULL)) return NULL; + if (zend_hash_num_elements(Z_ARRVAL_P(keyTypes)) < 2) return isList; + bool bleedingEdge; + if (UNEXPECTED(!isBleedingEdge(bleedingEdge))) return NULL; + if (!bleedingEdge) return isList; + zend_long value = pt_type_trinary_value(isList); + if (UNEXPECTED(value < 0)) return NULL; + return value == PT_TRI_YES ? pt_trinary_singleton(PT_TRI_MAYBE) : isList; + } + private: zend_object *self; @@ -1200,6 +1296,38 @@ bool pt_constant_array_type_builder_make_unsealed(zval *builder, zval *keyType, return !result.isUndef(); } +bool pt_constant_array_type_builder_make_key_order_known(zval *builder) +{ + bool native; + if (UNEXPECTED(!pt_catb_is_native(builder, native))) return false; + if (EXPECTED(native)) { + zv::ObjRef(Z_OBJ_P(builder)).propAtWrite(slots::keyOrderKnown, zv::Val::boolean(true)); + return true; + } + zv::Val result = pt_type_call(Z_OBJ_P(builder), PT_LC("makekeyorderknown"), 0, NULL); + return !result.isUndef(); +} + +bool pt_constant_array_type_builder_keep_key_order_of(zval *builder, zval *array) +{ + zv::Val known = pt_type_call(Z_OBJ_P(array), PT_LC("iskeyorderknown"), 0, NULL); + if (UNEXPECTED(known.isUndef())) return false; + if (!zend_is_true(known.raw())) return true; + return pt_constant_array_type_builder_make_key_order_known(builder); +} + +bool pt_constant_array_type_builder_forget_key_order(zval *builder) +{ + bool native; + if (UNEXPECTED(!pt_catb_is_native(builder, native))) return false; + if (EXPECTED(native)) { + zv::ObjRef(Z_OBJ_P(builder)).propAtWrite(slots::keyOrderKnown, zv::Val::boolean(false)); + return true; + } + zv::Val result = pt_type_call(Z_OBJ_P(builder), PT_LC("forgetkeyorder"), 0, NULL); + return !result.isUndef(); +} + bool pt_constant_array_type_builder_merge_unsealed(zval *builder, zval *keyType, zval *valueType) { bool native; @@ -1249,6 +1377,7 @@ PT_MINIT_REGISTRATION(pt_register_constant_array_type_builder) cls.privateTypedPropertyDefaultNull("degradeClosures", MAY_BE_BOOL); cls.privateTypedBoolProperty("oversized", false); cls.privateTypedClassProperty("isNonEmpty", ptcls::trinaryLogic, false); + cls.privateTypedBoolProperty("keyOrderKnown", false); cls.privateTypedProperty("keyTypes", MAY_BE_ARRAY); cls.privateTypedProperty("valueTypes", MAY_BE_ARRAY); cls.privateTypedProperty("nextAutoIndexes", MAY_BE_ARRAY); @@ -1276,6 +1405,28 @@ PT_MINIT_REGISTRATION(pt_register_constant_array_type_builder) PT_RETURN_VAL(pt_constant_array_type_builder_create_from_constant_array(startArrayType)); }); + cls.method(sigs::getListness, [](INTERNAL_FUNCTION_PARAMETERS) { + ZEND_PARSE_PARAMETERS_NONE(); + zval *listness = PT_THIS.listness(); + if (UNEXPECTED(listness == NULL)) RETURN_THROWS(); + RETURN_COPY(listness); + }); + + cls.method(sigs::makeKeyOrderKnown, [](INTERNAL_FUNCTION_PARAMETERS) { + ZEND_PARSE_PARAMETERS_NONE(); + zv::ObjRef(Z_OBJ_P(ZEND_THIS)).propAtWrite(slots::keyOrderKnown, zv::Val::boolean(true)); + }); + + cls.method(sigs::forgetKeyOrder, [](INTERNAL_FUNCTION_PARAMETERS) { + ZEND_PARSE_PARAMETERS_NONE(); + zv::ObjRef(Z_OBJ_P(ZEND_THIS)).propAtWrite(slots::keyOrderKnown, zv::Val::boolean(false)); + }); + + cls.method(sigs::forgetListKeyOrder, [](INTERNAL_FUNCTION_PARAMETERS) { + ZEND_PARSE_PARAMETERS_NONE(); + if (UNEXPECTED(!PT_THIS.forgetListKeyOrder())) RETURN_THROWS(); + }); + cls.method(sigs::makeUnsealed, [](INTERNAL_FUNCTION_PARAMETERS) { zval *keyType, *valueType; if (!zp::parse(execute_data, keyType, valueType)) RETURN_THROWS(); diff --git a/turbo-ext/src/ConstantTypeHelper.cpp b/turbo-ext/src/ConstantTypeHelper.cpp index 97b44fe90c2..c1d8b0ff079 100644 --- a/turbo-ext/src/ConstantTypeHelper.cpp +++ b/turbo-ext/src/ConstantTypeHelper.cpp @@ -84,6 +84,7 @@ class ConstantTypeHelper } zv::Val builder = pt_constant_array_type_builder_create_empty(); if (UNEXPECTED(builder.isUndef())) return zv::Val(); + if (UNEXPECTED(!pt_constant_array_type_builder_make_key_order_known(builder.raw()))) return zv::Val(); for (zv::ArrayEntry entry : zv::ArrRef(value)) { zv::Val keyType = keyTypeOf(entry); if (UNEXPECTED(keyType.isUndef())) return zv::Val(); diff --git a/turbo-ext/src/CountNarrowingHelper.cpp b/turbo-ext/src/CountNarrowingHelper.cpp index 4e2d2454c72..f1874e4963c 100644 --- a/turbo-ext/src/CountNarrowingHelper.cpp +++ b/turbo-ext/src/CountNarrowingHelper.cpp @@ -97,6 +97,75 @@ zv::Val setRootExpr(zv::Val specifiedTypes, zval *rootExpr) return pt_specified_types_set_root_expr(Z_OBJ_P(specifiedTypes.raw()), rootExpr); } +/* new ConstantIntegerType($value)->isSuperTypeOf($type)->yes(); false = pending exception */ +bool isExactly(zend_long value, zval *type, bool &out) +{ + zval constant; + if (UNEXPECTED(!pt_constant_integer_type_new(&constant, value))) return false; + zv::Val constantType = zv::Val::adopt(constant); + zend_long result = superTypeOf(constantType.raw(), type); + if (UNEXPECTED(result < 0)) return false; + out = result == PT_TRI_YES; + return true; +} + +/* private narrowShapeToSize(ConstantArrayType $arrayType, Type $sizeType): 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; UNDEF = pending exception */ +zv::Val narrowShapeToSize(zval *arrayType, zval *sizeType) +{ + zend_object *arrayObject = Z_OBJ_P(arrayType); + zv::Val optionalKeys = pt_type_call(arrayObject, PT_LC("getoptionalkeys"), 0, NULL); + if (UNEXPECTED(optionalKeys.isUndef())) return zv::Val(); + if (Z_TYPE_P(optionalKeys.raw()) != IS_ARRAY || zend_hash_num_elements(Z_ARRVAL_P(optionalKeys.raw())) == 0) { + return zv::Val::copyOf(zv::Ref(arrayType)); + } + zv::Val unsealed = pt_type_call(arrayObject, PT_LC("isunsealed"), 0, NULL); + if (UNEXPECTED(unsealed.isUndef())) return zv::Val(); + zend_long unsealedness = pt_type_trinary_value(unsealed.raw()); + if (UNEXPECTED(unsealedness < 0)) return zv::Val(); + if (unsealedness != PT_TRI_NO) return zv::Val::copyOf(zv::Ref(arrayType)); + + zv::Val keyTypes = pt_type_call(arrayObject, PT_LC("getkeytypes"), 0, NULL); + if (UNEXPECTED(keyTypes.isUndef())) return zv::Val(); + if (UNEXPECTED(Z_TYPE_P(keyTypes.raw()) != IS_ARRAY)) { + zend_throw_error(NULL, "getKeyTypes() must return an array"); + return zv::Val(); + } + zv::Val arraySize = arraySizeOf(arrayType); + if (UNEXPECTED(arraySize.isUndef())) return zv::Val(); + zv::Args intersectArgs{sizeType, arraySize.raw()}; + zv::Val size = pt_type_combinator_intersect(2, intersectArgs); + if (UNEXPECTED(size.isUndef())) return zv::Val(); + + zend_long keyCount = (zend_long) zend_hash_num_elements(Z_ARRVAL_P(keyTypes.raw())); + zend_long optionalCount = (zend_long) zend_hash_num_elements(Z_ARRVAL_P(optionalKeys.raw())); + bool onlyRequired; + if (UNEXPECTED(!isExactly(keyCount - optionalCount, size.raw(), onlyRequired))) return zv::Val(); + bool all = false; + if (!onlyRequired && UNEXPECTED(!isExactly(keyCount, size.raw(), all))) return zv::Val(); + if (!onlyRequired && !all) return zv::Val::copyOf(zv::Ref(arrayType)); + + zv::Val narrowed = zv::Val::copyOf(zv::Ref(arrayType)); + for (zv::ArrayEntry entry : zv::TableRef(Z_ARRVAL_P(optionalKeys.raw()))) { + zval *index = entry.value().deref().raw(); + zval *keyType = Z_TYPE_P(index) == IS_LONG ? zend_hash_index_find(Z_ARRVAL_P(keyTypes.raw()), (zend_ulong) Z_LVAL_P(index)) : NULL; + if (UNEXPECTED(keyType == NULL)) { + zend_throw_error(NULL, "An optional key has no key type"); + return zv::Val(); + } + if (onlyRequired) { + narrowed = pt_type_call(Z_OBJ_P(narrowed.raw()), PT_LC("unsetoffset"), 1, keyType); + } else { + narrowed = pt_type_call(Z_OBJ_P(narrowed.raw()), PT_LC("makeoffsetrequired"), 1, keyType); + } + if (UNEXPECTED(narrowed.isUndef())) return zv::Val(); + } + + return narrowed; +} + /* TypeCombinator::union(...$types) of a list built by push */ zv::Val unionOf(zv::Arr &types) { @@ -307,10 +376,19 @@ class CountNarrowingHelper if (isList == PT_TRI_YES) { resultType = pt_type_call(Z_OBJ_P(arrayType), PT_LC("truncatelisttosize"), 1, sizeType); } else { + zv::Val narrowedArrayType = zv::Val::copyOf(zv::Ref(arrayType)); + zv::Val constantArrays = pt_type_call(Z_OBJ_P(arrayType), PT_LC("getconstantarrays"), 0, NULL); + if (UNEXPECTED(constantArrays.isUndef())) return zv::Val(); + if (Z_TYPE_P(constantArrays.raw()) == IS_ARRAY) { + for (zv::ArrayEntry constantEntry : zv::TableRef(Z_ARRVAL_P(constantArrays.raw()))) { + narrowedArrayType = narrowShapeToSize(constantEntry.value().deref().raw(), sizeType); + if (UNEXPECTED(narrowedArrayType.isUndef())) return zv::Val(); + } + } zval nonEmpty; if (UNEXPECTED(!pt_non_empty_array_type_new(&nonEmpty))) return zv::Val(); zv::Val nonEmptyType = zv::Val::adopt(nonEmpty); - zv::Args intersectArgs{arrayType, nonEmptyType.raw()}; + zv::Args intersectArgs{narrowedArrayType.raw(), nonEmptyType.raw()}; resultType = pt_type_combinator_intersect(2, intersectArgs); } if (UNEXPECTED(resultType.isUndef())) return zv::Val(); diff --git a/turbo-ext/src/FuncCallScopeEffectsHelper.cpp b/turbo-ext/src/FuncCallScopeEffectsHelper.cpp index 463b8276400..9632f77d114 100644 --- a/turbo-ext/src/FuncCallScopeEffectsHelper.cpp +++ b/turbo-ext/src/FuncCallScopeEffectsHelper.cpp @@ -1092,6 +1092,7 @@ class FuncCallScopeEffectsHelper ? pt_constant_array_type_builder_create_empty() : pt_constant_array_type_builder_create_from_constant_array(constantArrayIn); if (UNEXPECTED(arrayTypeBuilder.isUndef())) return zv::Val(); + if (prepend && UNEXPECTED(!pt_constant_array_type_builder_keep_key_order_of(arrayTypeBuilder.raw(), constantArrayIn))) return zv::Val(); auto setOnBuilder = [&](zval *offsetType, zval *valueType, bool optional) -> bool { return pt_constant_array_type_builder_set_offset_value_type(arrayTypeBuilder.raw(), offsetType, valueType, optional); @@ -1286,6 +1287,7 @@ class FuncCallScopeEffectsHelper zv::Val firstHold = zv::Val::copyOf(zv::Ref(first)); zv::Val builder = pt_constant_array_type_builder_create_empty(); if (UNEXPECTED(builder.isUndef())) return zv::Val(); + if (UNEXPECTED(!pt_constant_array_type_builder_keep_key_order_of(builder.raw(), firstHold.raw()))) return zv::Val(); zv::Arr intValues = zv::Arr::empty(); zv::Val keyTypes = typeOpOn(firstHold.raw(), PT_OP_GET_KEY_TYPES, "getKeyTypes"); diff --git a/turbo-ext/src/IetrSupport.h b/turbo-ext/src/IetrSupport.h index beaf156191b..fb8c8115d5f 100644 --- a/turbo-ext/src/IetrSupport.h +++ b/turbo-ext/src/IetrSupport.h @@ -95,6 +95,8 @@ inline constexpr Method mIsEnum{"isEnum"}; inline constexpr Method mIsTrue{"isTrue"}; inline constexpr Method mIsFalse{"isFalse"}; inline constexpr Method mIsConstantArray{"isConstantArray", PT_OP_IS_CONSTANT_ARRAY}; +inline constexpr Method mInRenumberingOrder{"inRenumberingOrder"}; +inline constexpr Method mIsKeyOrderKnown{"isKeyOrderKnown"}; inline constexpr Method mIsConstantScalarValue{"isConstantScalarValue", PT_OP_IS_CONSTANT_SCALAR_VALUE}; inline constexpr Method mIsClassString{"isClassString"}; inline constexpr Method mIsIterableAtLeastOnce{"isIterableAtLeastOnce", PT_OP_IS_ITERABLE_AT_LEAST_ONCE}; diff --git a/turbo-ext/src/InitializerExprTypeResolver.cpp b/turbo-ext/src/InitializerExprTypeResolver.cpp index 0f873524ffc..977c7835b27 100644 --- a/turbo-ext/src/InitializerExprTypeResolver.cpp +++ b/turbo-ext/src/InitializerExprTypeResolver.cpp @@ -948,6 +948,88 @@ class InitializerExprTypeResolver IETR_VAL(rightValueTypes, callOn(rightType, mGetValueTypes)); if (UNEXPECTED(!requireArray(leftKeyTypes.raw()) || !requireArray(rightKeyTypesHold.raw()) || !requireArray(leftValueTypes.raw()) || !requireArray(rightValueTypes.raw()))) return zv::Val(); + /* $valueComparisonCallback($leftValueType, $rightValueType) */ + auto compareValues = [&](zval *leftValueType, zval *rightValueType) -> zv::Val { + zval nullValue; + ZVAL_NULL(&nullValue); + zval *leftValue = leftValueType != NULL ? leftValueType : &nullValue; + zval *rightValue = rightValueType != NULL ? rightValueType : &nullValue; + if (valueComparisonCallback != NULL) { + zv::Args argv{leftValue, rightValue}; + return pt_type_call_callable(valueComparisonCallback, 2, argv); + } + return identical ? resolveIdenticalType(leftValue, rightValue) : resolveEqualType(leftValue, rightValue, phpVersions); + }; + + IETR_VAL(leftKeyOrderKnown, pt_type_call(Z_OBJ_P(leftType), PT_LC("iskeyorderknown"), 0, NULL)); + IETR_VAL(rightKeyOrderKnown, pt_type_call(Z_OBJ_P(rightType), PT_LC("iskeyorderknown"), 0, NULL)); + if (!zend_is_true(leftKeyOrderKnown.raw()) || !zend_is_true(rightKeyOrderKnown.raw())) { + /* a shape that does not know its key order is compared key by + * key, and it is never certainly identical to another array */ + zv::Arr rightKeyIndexes = zv::Arr::create(zend_hash_num_elements(Z_ARRVAL_P(rightKeyTypesHold.raw()))); + for (zv::ArrayEntry rightEntry : zv::ArrRef(rightKeyTypesHold.raw())) { + IETR_VAL(keyValue, pt_type_call(Z_OBJ_P(rightEntry.value().deref().raw()), PT_LC("getvalue"), 0, NULL)); + zval jZv; + entryKey(rightEntry, jZv); + if (Z_TYPE_P(keyValue.raw()) == IS_LONG) { + zend_hash_index_update(rightKeyIndexes.table(), Z_LVAL_P(keyValue.raw()), &jZv); + } else { + zend_symtable_update(rightKeyIndexes.table(), Z_STR_P(keyValue.raw()), &jZv); + } + } + + for (zv::ArrayEntry leftEntry : zv::ArrRef(leftKeyTypes.raw())) { + zval i; + entryKey(leftEntry, i); + IETR_VAL(keyValue, pt_type_call(Z_OBJ_P(leftEntry.value().deref().raw()), PT_LC("getvalue"), 0, NULL)); + zval *found = Z_TYPE_P(keyValue.raw()) == IS_LONG + ? zend_hash_index_find(rightKeyIndexes.table(), Z_LVAL_P(keyValue.raw())) + : zend_symtable_find(rightKeyIndexes.table(), Z_STR_P(keyValue.raw())); + if (found == NULL) { + IETR_VAL(leftOptionalHold, callOn(leftType, mIsOptionalKey, 1, &i)); + if (!zend_is_true(leftOptionalHold.raw())) { + return newTypeResult(newConstantBooleanType(false)); + } + continue; + } + zval jFound; + ZVAL_COPY_VALUE(&jFound, found); + if (Z_TYPE_P(keyValue.raw()) == IS_LONG) { + zend_hash_index_del(rightKeyIndexes.table(), Z_LVAL_P(keyValue.raw())); + } else { + zend_symtable_del(rightKeyIndexes.table(), Z_STR_P(keyValue.raw())); + } + + IETR_VAL(leftOptionalHold, callOn(leftType, mIsOptionalKey, 1, &i)); + if (zend_is_true(leftOptionalHold.raw())) { + IETR_VAL(rightOptionalHold, callOn(rightType, mIsOptionalKey, 1, &jFound)); + if (zend_is_true(rightOptionalHold.raw())) continue; + } + + zval *leftValueType = arrayOffsetForRead(leftValueTypes.raw(), &i); + if (UNEXPECTED(leftValueType == NULL && EG(exception) != NULL)) return zv::Val(); + zval *rightValueType = arrayOffsetForRead(rightValueTypes.raw(), &jFound); + if (UNEXPECTED(rightValueType == NULL && EG(exception) != NULL)) return zv::Val(); + zv::Val comparison = compareValues(leftValueType, rightValueType); + if (UNEXPECTED(comparison.isUndef())) return zv::Val(); + IETR_VAL(comparisonType, typeResultType(comparison.raw())); + IETR_VAL(comparisonBooleanType, callOn(comparisonType.raw(), mToBoolean)); + IETR_TRI(isFalse, triOn(comparisonBooleanType.raw(), mIsFalse)); + if (isFalse == PT_TRI_YES) { + return comparison; + } + } + + for (zv::ArrayEntry rest : rightKeyIndexes.arrRef()) { + IETR_VAL(rightOptionalHold, callOn(rightType, mIsOptionalKey, 1, rest.value().deref().raw())); + if (!zend_is_true(rightOptionalHold.raw())) { + return newTypeResult(newConstantBooleanType(false)); + } + } + + return newTypeResult(newBooleanType()); + } + IETR_VAL(resultTypeInit, newConstantBooleanType(true)); zv::Val resultType = std::move(resultTypeInit); @@ -1023,17 +1105,7 @@ class InitializerExprTypeResolver if (UNEXPECTED(leftValueType == NULL && EG(exception) != NULL)) return zv::Val(); zval *rightValueType = arrayOffsetForRead(rightValueTypes.raw(), &j); if (UNEXPECTED(rightValueType == NULL && EG(exception) != NULL)) return zv::Val(); - zval nullValue; - ZVAL_NULL(&nullValue); - zval *leftValue = leftValueType != NULL ? leftValueType : &nullValue; - zval *rightValue = rightValueType != NULL ? rightValueType : &nullValue; - zv::Val leftIdenticalToRightResult; - if (valueComparisonCallback != NULL) { - zv::Args argv{leftValue, rightValue}; - leftIdenticalToRightResult = pt_type_call_callable(valueComparisonCallback, 2, argv); - } else { - leftIdenticalToRightResult = identical ? resolveIdenticalType(leftValue, rightValue) : resolveEqualType(leftValue, rightValue, phpVersions); - } + zv::Val leftIdenticalToRightResult = compareValues(leftValueType, rightValueType); if (UNEXPECTED(leftIdenticalToRightResult.isUndef())) return zv::Val(); IETR_VAL(leftIdenticalToRight, typeResultType(leftIdenticalToRightResult.raw())); IETR_TRI(isFalse, triOn(leftIdenticalToRight.raw(), mIsFalse)); @@ -1704,6 +1776,7 @@ class InitializerExprTypeResolver } IETR_VAL(arrayBuilder, pt_constant_array_type_builder_create_empty()); + if (UNEXPECTED(!pt_constant_array_type_builder_make_key_order_known(arrayBuilder.raw()))) return zv::Val(); zval isList; ZVAL_NULL(&isList); zv::Arr hasOffsetValueTypes = zv::Arr::create(0); @@ -1843,7 +1916,13 @@ class InitializerExprTypeResolver zv::Arr keyTypeArrays = zv::Arr::create(totalArrays); for (zv::ArrayEntry arrayEntry : zv::ArrRef(constantArrays)) { - zval *constantArrayType = arrayEntry.value().raw(); + // the integer keys are renumbered in the order the array has them + zv::Val renumberedArray = callOn(arrayEntry.value().raw(), mInRenumberingOrder); + if (UNEXPECTED(renumberedArray.isUndef())) return false; + zval *constantArrayType = renumberedArray.raw(); + zv::Val keyOrderKnown = callOn(constantArrayType, mIsKeyOrderKnown); + if (UNEXPECTED(keyOrderKnown.isUndef())) return false; + if (!zend_is_true(keyOrderKnown.raw()) && UNEXPECTED(!pt_constant_array_type_builder_forget_key_order(arrayBuilder))) return false; size_t nextIntegerSlot = 0; zv::Val keyTypes = callOn(constantArrayType, mGetKeyTypes); if (UNEXPECTED(keyTypes.isUndef())) return false; diff --git a/turbo-ext/src/IntersectionType.cpp b/turbo-ext/src/IntersectionType.cpp index 8a97d0a6b6a..e2f6316983a 100644 --- a/turbo-ext/src/IntersectionType.cpp +++ b/turbo-ext/src/IntersectionType.cpp @@ -1391,7 +1391,8 @@ class IntersectionType return intersectCall(PT_LC("getiterablekeytype"), 0, NULL); } - zv::Val getFirstIterableKeyType() const { return intersectCall(PT_LC("getiterablekeytype"), 0, NULL); } + zv::Val getFirstIterableKeyType() const { return intersectCall(PT_LC("getfirstiterablekeytype"), 0, NULL); } + zv::Val getLastIterableKeyType() const { return intersectCall(PT_LC("getlastiterablekeytype"), 0, NULL); } /* the members' value types intersected, narrowed to object|non-falsy-string * for a callable array */ @@ -1409,7 +1410,8 @@ class IntersectionType return result; } - zv::Val getFirstIterableValueType() const { return intersectCall(PT_LC("getiterablevaluetype"), 0, NULL); } + zv::Val getFirstIterableValueType() const { return intersectCall(PT_LC("getfirstiterablevaluetype"), 0, NULL); } + zv::Val getLastIterableValueType() const { return intersectCall(PT_LC("getlastiterablevaluetype"), 0, NULL); } /* the memoized is*() family */ zend_long isArray() const { return memoizedCall(slots::isArray, PT_LC("isarray")); } @@ -3520,7 +3522,7 @@ PT_MINIT_REGISTRATION(pt_register_intersection_type) pt_it_value0(INTERNAL_FUNCTION_PARAM_PASSTHRU, &IntersectionType::getFirstIterableKeyType); }); cls.method(sigs::getLastIterableKeyType, [](INTERNAL_FUNCTION_PARAMETERS) { - pt_it_value0(INTERNAL_FUNCTION_PARAM_PASSTHRU, &IntersectionType::getFirstIterableKeyType); + pt_it_value0(INTERNAL_FUNCTION_PARAM_PASSTHRU, &IntersectionType::getLastIterableKeyType); }); cls.method(sigs::getIterableValueType, [](INTERNAL_FUNCTION_PARAMETERS) { pt_it_value0(INTERNAL_FUNCTION_PARAM_PASSTHRU, &IntersectionType::getIterableValueType); @@ -3530,7 +3532,7 @@ PT_MINIT_REGISTRATION(pt_register_intersection_type) pt_it_value0(INTERNAL_FUNCTION_PARAM_PASSTHRU, &IntersectionType::getFirstIterableValueType); }); cls.method(sigs::getLastIterableValueType, [](INTERNAL_FUNCTION_PARAMETERS) { - pt_it_value0(INTERNAL_FUNCTION_PARAM_PASSTHRU, &IntersectionType::getFirstIterableValueType); + pt_it_value0(INTERNAL_FUNCTION_PARAM_PASSTHRU, &IntersectionType::getLastIterableValueType); }); cls.method(sigs::isArray, [](INTERNAL_FUNCTION_PARAMETERS) { diff --git a/turbo-ext/src/LateResolvableArrayShapeType.cpp b/turbo-ext/src/LateResolvableArrayShapeType.cpp index 82e0edc8898..bb6cc1de2f4 100644 --- a/turbo-ext/src/LateResolvableArrayShapeType.cpp +++ b/turbo-ext/src/LateResolvableArrayShapeType.cpp @@ -31,6 +31,28 @@ zend_class_entry *pt_ce_late_resolvable_array_shape_type = nullptr; namespace phpstanturbo { +/* BleedingEdgeToggle::isBleedingEdge(): the private static the final class + * returns, read through the engine's static-property path under the class's + * own scope (as ConstantArrayType.cpp reads it); false = pending exception */ +static bool isBleedingEdge(bool &out) +{ + zend_class_entry *ce = pt_class(PT_CLASS_BLEEDING_EDGE_TOGGLE); + if (UNEXPECTED(ce == NULL)) return false; + auto previousScope = EG(fake_scope); /* const from PHP 8.4 */ + EG(fake_scope) = ce; + zval *value = zend_read_static_property(ce, PT_LC("bleedingEdge"), 1); + EG(fake_scope) = previousScope; + if (EXPECTED(value != NULL && (Z_TYPE_P(value) == IS_TRUE || Z_TYPE_P(value) == IS_FALSE))) { + out = Z_TYPE_P(value) == IS_TRUE; + return true; + } + if (UNEXPECTED(EG(exception))) return false; + zv::Val result = pt_type_call_static(PT_CLASS_BLEEDING_EDGE_TOGGLE, PT_LC("isbleedingedge"), 0, NULL); + if (UNEXPECTED(result.isUndef())) return false; + out = zend_is_true(result.raw()); + return true; +} + /* Mirrors PHPStan\Type\LateResolvableArrayShapeType. State lives in the * PHP object's slots. */ class LateResolvableArrayShapeType @@ -266,6 +288,18 @@ class LateResolvableArrayShapeType if (UNEXPECTED(set.isUndef())) return zv::Val(); } + /* a shape that names its keys only says they are present, not in which order */ + if (zend_hash_num_elements(explicitKeyValues.table()) == 0) { + if (UNEXPECTED(!pt_constant_array_type_builder_make_key_order_known(builder.raw()))) return zv::Val(); + } else { + bool bleedingEdge; + if (UNEXPECTED(!isBleedingEdge(bleedingEdge))) return zv::Val(); + if (bleedingEdge) { + zv::Val forgotten = pt_type_call(Z_OBJ_P(builder.raw()), PT_LC("forgetlistkeyorder"), 0, NULL); + if (UNEXPECTED(forgotten.isUndef())) return zv::Val(); + } + } + bool isList; if (UNEXPECTED(!kindIsList(isList))) return zv::Val(); diff --git a/turbo-ext/src/MutatingScope.cpp b/turbo-ext/src/MutatingScope.cpp index 7e75eac9f0d..a52a94fc13d 100644 --- a/turbo-ext/src/MutatingScope.cpp +++ b/turbo-ext/src/MutatingScope.cpp @@ -11099,6 +11099,35 @@ class MutatingScope if (UNEXPECTED(keyTypes.isUndef())) return zv::Val(); zv::Val flattenedKeys = pt_type_utils_flatten_types(keyTypes.raw()); if (UNEXPECTED(flattenedKeys.isUndef() || Z_TYPE_P(flattenedKeys.raw()) != IS_ARRAY)) return zv::Val(); + + /* 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 */ + zv::Val aShapes = pt_type_op(Z_OBJ_P(a), PT_OP_GET_CONSTANT_ARRAYS, 0, NULL); + if (UNEXPECTED(aShapes.isUndef() || Z_TYPE_P(aShapes.raw()) != IS_ARRAY)) return zv::Val(); + zv::Val bShapes = pt_type_op(Z_OBJ_P(b), PT_OP_GET_CONSTANT_ARRAYS, 0, NULL); + if (UNEXPECTED(bShapes.isUndef() || Z_TYPE_P(bShapes.raw()) != IS_ARRAY)) return zv::Val(); + if (zend_hash_num_elements(Z_ARRVAL_P(aShapes.raw())) == 1 && zend_hash_num_elements(Z_ARRVAL_P(bShapes.raw())) == 1) { + zval *aShape = zend_hash_index_find(Z_ARRVAL_P(aShapes.raw()), 0); + zval *bShape = zend_hash_index_find(Z_ARRVAL_P(bShapes.raw()), 0); + if (UNEXPECTED(aShape == NULL || bShape == NULL)) return zv::Val(); + zv::Args mergedArgs{bShape}; + zv::Val mergedKeyTypes = pt_type_call(Z_OBJ_P(aShape), PT_LC("getkeytypesinmergedorderwith"), 1, mergedArgs); + if (UNEXPECTED(mergedKeyTypes.isUndef())) return zv::Val(); + zv::Val aKeyTypes = pt_type_call(Z_OBJ_P(aShape), PT_LC("getkeytypes"), 0, NULL); + if (UNEXPECTED(aKeyTypes.isUndef() || Z_TYPE_P(aKeyTypes.raw()) != IS_ARRAY)) return zv::Val(); + zv::Val bKeyTypes = pt_type_call(Z_OBJ_P(bShape), PT_LC("getkeytypes"), 0, NULL); + if (UNEXPECTED(bKeyTypes.isUndef() || Z_TYPE_P(bKeyTypes.raw()) != IS_ARRAY)) return zv::Val(); + if ( + Z_TYPE_P(mergedKeyTypes.raw()) == IS_ARRAY + && zend_hash_num_elements(Z_ARRVAL_P(mergedKeyTypes.raw())) == zend_hash_num_elements(Z_ARRVAL_P(flattenedKeys.raw())) + && zend_hash_num_elements(Z_ARRVAL_P(mergedKeyTypes.raw())) == zend_hash_num_elements(Z_ARRVAL_P(aKeyTypes.raw())) + && zend_hash_num_elements(Z_ARRVAL_P(mergedKeyTypes.raw())) == zend_hash_num_elements(Z_ARRVAL_P(bKeyTypes.raw())) + ) { + flattenedKeys = std::move(mergedKeyTypes); + if (UNEXPECTED(!pt_constant_array_type_builder_make_key_order_known(builder.raw()))) return zv::Val(); + } + } + for (auto keyEntry : zv::TableRef(Z_ARRVAL_P(flattenedKeys.raw()))) { zv::Ref keyType = keyEntry.value().deref(); zend_long hasA = typeOpTrinary(Z_OBJ_P(a), PT_OP_HAS_OFFSET_VALUE_TYPE, 1, keyType.raw()); diff --git a/turbo-ext/src/PhpClassReflectionExtension.cpp b/turbo-ext/src/PhpClassReflectionExtension.cpp index 6a86a449273..b3e7844fd1e 100644 --- a/turbo-ext/src/PhpClassReflectionExtension.cpp +++ b/turbo-ext/src/PhpClassReflectionExtension.cpp @@ -1541,6 +1541,7 @@ class PhpClassReflectionExtension if (zend_string_equals_literal(lowered.get(), "cases")) { zv::Val builder = pt_constant_array_type_builder_create_empty(); if (UNEXPECTED(builder.isUndef())) return zv::Val(); + if (UNEXPECTED(!pt_constant_array_type_builder_make_key_order_known(builder.raw()))) return zv::Val(); zv::Val enumCases = call(classReflection, PT_LC("getenumcases")); if (UNEXPECTED(!arrayResult(enumCases, "PHPStan\\Reflection\\ClassReflection::getEnumCases"))) return zv::Val(); zv::Val ownerName = pt_class_reflection_get_name(Z_OBJ_P(classReflection)); diff --git a/turbo-ext/src/StaticType.cpp b/turbo-ext/src/StaticType.cpp index 5d847f7f009..1ae44c56c03 100644 --- a/turbo-ext/src/StaticType.cpp +++ b/turbo-ext/src/StaticType.cpp @@ -1141,23 +1141,21 @@ PT_MINIT_REGISTRATION(pt_register_static_type) stDelegate(INTERNAL_FUNCTION_PARAM_PASSTHRU, PT_LC("getiterablekeytype"), 0, 0); }); cls.op(PT_OP_GET_ITERABLE_KEY_TYPE, PT_OP_LAMBDA { return StaticType(self).delegateOp(PT_OP_GET_ITERABLE_KEY_TYPE, argc, argv); }); - /* the first/last variants delegate to the plain key/value ones, as - * the twin does */ cls.method(sigs::getFirstIterableKeyType, [](INTERNAL_FUNCTION_PARAMETERS) { - stDelegate(INTERNAL_FUNCTION_PARAM_PASSTHRU, PT_LC("getiterablekeytype"), 0, 0); + stDelegate(INTERNAL_FUNCTION_PARAM_PASSTHRU, PT_LC("getfirstiterablekeytype"), 0, 0); }); cls.method(sigs::getLastIterableKeyType, [](INTERNAL_FUNCTION_PARAMETERS) { - stDelegate(INTERNAL_FUNCTION_PARAM_PASSTHRU, PT_LC("getiterablekeytype"), 0, 0); + stDelegate(INTERNAL_FUNCTION_PARAM_PASSTHRU, PT_LC("getlastiterablekeytype"), 0, 0); }); cls.method(sigs::getIterableValueType, [](INTERNAL_FUNCTION_PARAMETERS) { stDelegate(INTERNAL_FUNCTION_PARAM_PASSTHRU, PT_LC("getiterablevaluetype"), 0, 0); }); cls.op(PT_OP_GET_ITERABLE_VALUE_TYPE, PT_OP_LAMBDA { return StaticType(self).delegateOp(PT_OP_GET_ITERABLE_VALUE_TYPE, argc, argv); }); cls.method(sigs::getFirstIterableValueType, [](INTERNAL_FUNCTION_PARAMETERS) { - stDelegate(INTERNAL_FUNCTION_PARAM_PASSTHRU, PT_LC("getiterablevaluetype"), 0, 0); + stDelegate(INTERNAL_FUNCTION_PARAM_PASSTHRU, PT_LC("getfirstiterablevaluetype"), 0, 0); }); cls.method(sigs::getLastIterableValueType, [](INTERNAL_FUNCTION_PARAMETERS) { - stDelegate(INTERNAL_FUNCTION_PARAM_PASSTHRU, PT_LC("getiterablevaluetype"), 0, 0); + stDelegate(INTERNAL_FUNCTION_PARAM_PASSTHRU, PT_LC("getlastiterablevaluetype"), 0, 0); }); cls.method(sigs::isOffsetAccessible, [](INTERNAL_FUNCTION_PARAMETERS) { stDelegate(INTERNAL_FUNCTION_PARAM_PASSTHRU, PT_LC("isoffsetaccessible"), 0, 0); diff --git a/turbo-ext/src/TemplateConstantArrayType.cpp b/turbo-ext/src/TemplateConstantArrayType.cpp index 80bf6f94eac..54050f10518 100644 --- a/turbo-ext/src/TemplateConstantArrayType.cpp +++ b/turbo-ext/src/TemplateConstantArrayType.cpp @@ -29,7 +29,8 @@ class TemplateConstantArrayType /* __construct($scope, $templateTypeStrategy, $templateTypeVariance, $name, $bound, $default); every argument borrowed ($defaultType NULL or IS_NULL for null); false = pending exception */ [[nodiscard]] bool construct(zval *scope, zval *strategy, zval *variance, zend_string *name, zval *bound, zval *defaultType) const { - /* parent::__construct($bound->getKeyTypes(), $bound->getValueTypes(), $bound->getNextAutoIndexes(), $bound->getOptionalKeys(), $bound->isList()) */ + /* parent::__construct($bound->getKeyTypes(), $bound->getValueTypes(), $bound->getNextAutoIndexes(), $bound->getOptionalKeys(), $bound->isList(), + * keyOrderKnown: $bound->isKeyOrderKnown()) */ zv::Val keyTypes = pt_type_call(Z_OBJ_P(bound), PT_LC("getkeytypes"), 0, NULL); if (UNEXPECTED(keyTypes.isUndef())) return false; zv::Val valueTypes = pt_type_call(Z_OBJ_P(bound), PT_LC("getvaluetypes"), 0, NULL); @@ -40,8 +41,12 @@ class TemplateConstantArrayType if (UNEXPECTED(optionalKeys.isUndef())) return false; zv::Val isList = pt_type_op(Z_OBJ_P(bound), PT_OP_IS_LIST, 0, NULL); if (UNEXPECTED(isList.isUndef())) return false; - zv::Args args{keyTypes.raw(), valueTypes.raw(), nextAutoIndexes.raw(), optionalKeys.raw(), isList.raw()}; - if (UNEXPECTED(!pt_template_type_parent_construct(self, pt_ce_template_constant_array_type, 5, args))) return false; + zv::Val keyOrderKnown = pt_type_call(Z_OBJ_P(bound), PT_LC("iskeyorderknown"), 0, NULL); + if (UNEXPECTED(keyOrderKnown.isUndef())) return false; + zval nullZv; + ZVAL_NULL(&nullZv); + zv::Args args{keyTypes.raw(), valueTypes.raw(), nextAutoIndexes.raw(), optionalKeys.raw(), isList.raw(), &nullZv, keyOrderKnown.raw()}; + if (UNEXPECTED(!pt_template_type_parent_construct(self, pt_ce_template_constant_array_type, 7, args))) return false; pt_template_type_init(self, pt_ce_template_constant_array_type, scope, strategy, variance, name, bound, defaultType); return true; } @@ -58,15 +63,17 @@ class TemplateConstantArrayType zv::Val rebuild(zv::Val bound) const { return pt_template_type_rebuild(self, pt_ce_template_constant_array_type, std::move(bound)); } /* protected recreate(): new self($this->scope, $this->strategy, $this->variance, $this->name, new ConstantArrayType($keyTypes, - * $valueTypes, $nextAutoIndexes, $optionalKeys, $isList, $this->keepUnsealedDeclaration($unsealed)), $this->default) */ + * $valueTypes, $nextAutoIndexes, $optionalKeys, $isList, $this->keepUnsealedDeclaration($unsealed), $this->isKeyOrderKnown()), $this->default) */ zv::Val recreate(zval *keyTypes, zval *valueTypes, zval *nextAutoIndexes, zval *optionalKeys, zval *isList, zval *unsealed) const { zval nullZv; ZVAL_NULL(&nullZv); zv::Val kept = pt_constant_array_type_keep_unsealed_declaration(self, unsealed != NULL ? unsealed : &nullZv); if (UNEXPECTED(kept.isUndef())) return zv::Val(); + zv::Val keyOrderKnown = pt_type_call(self, PT_LC("iskeyorderknown"), 0, NULL); + if (UNEXPECTED(keyOrderKnown.isUndef())) return zv::Val(); zval constantArray; - if (UNEXPECTED(!pt_constant_array_type_new(&constantArray, keyTypes, valueTypes, nextAutoIndexes, optionalKeys, isList, kept.raw()))) return zv::Val(); + if (UNEXPECTED(!pt_constant_array_type_new(&constantArray, keyTypes, valueTypes, nextAutoIndexes, optionalKeys, isList, kept.raw(), zend_is_true(keyOrderKnown.raw())))) return zv::Val(); return rebuild(zv::Val::adopt(constantArray)); } diff --git a/turbo-ext/src/TemplateTypeHelper.cpp b/turbo-ext/src/TemplateTypeHelper.cpp index 691fad0308b..20790013aa0 100644 --- a/turbo-ext/src/TemplateTypeHelper.cpp +++ b/turbo-ext/src/TemplateTypeHelper.cpp @@ -161,10 +161,18 @@ class TemplateTypeHelper generalize = !boundIsScalar || isArrayKey; } } - if (!generalize) return zv::Val::copyOf(zv::Ref(type)); - zv::Val precision = pt_type_call_static(PT_CLASS_GENERALIZE_PRECISION, PT_LC("templateargument"), 0, NULL); - if (UNEXPECTED(precision.isUndef())) return zv::Val(); - return pt_type_call(Z_OBJ_P(type), PT_LC("generalize"), 1, precision.raw()); + zv::Val generalized; + if (generalize) { + zv::Val precision = pt_type_call_static(PT_CLASS_GENERALIZE_PRECISION, PT_LC("templateargument"), 0, NULL); + if (UNEXPECTED(precision.isUndef())) return zv::Val(); + generalized = pt_type_call(Z_OBJ_P(type), PT_LC("generalize"), 1, precision.raw()); + if (UNEXPECTED(generalized.isUndef())) return zv::Val(); + } else { + generalized = zv::Val::copyOf(zv::Ref(type)); + } + + /* the order of the keys of an array written in code is as specific as its values */ + return mapWith(generalized.raw(), forgetKeyOrderCallback); } private: @@ -205,6 +213,7 @@ class TemplateTypeHelper static void resolveToBoundsCallback(zval *state0, zval *state1, uint32_t argc, zval *argv, zval *return_value); static void toArgumentCallback(zval *state0, zval *state1, uint32_t argc, zval *argv, zval *return_value); static void removeFinalByKeywordOverridesCallback(zval *state0, zval *state1, uint32_t argc, zval *argv, zval *return_value); + static void forgetKeyOrderCallback(zval *state0, zval *state1, uint32_t argc, zval *argv, zval *return_value); }; zv::Val TemplateTypeHelper::resolveTemplateTypes(zval *type, zval *standins, zval *callSiteVariances, zval *positionVariance, bool keepErrorTypes) @@ -603,6 +612,27 @@ void TemplateTypeHelper::removeFinalByKeywordOverridesCallback(zval *state0, zva (void) pt_type_traverser_traverse(return_value, traverse, type); } +/* generalizeInferredTemplateType()'s closure: a ConstantArrayType that is + * not a TemplateType replaced by its forgetKeyOrder() */ +void TemplateTypeHelper::forgetKeyOrderCallback(zval *state0, zval *state1, uint32_t argc, zval *argv, zval *return_value) +{ + (void) state0; + (void) state1; + zval *type, *traverse; + if (UNEXPECTED(!pt_tth_callback_args(argc, argv, type, traverse))) return; + if (zv::Ref(type).instanceOf(pt_ce_constant_array_type)) { + bool isTemplate; + if (UNEXPECTED(!pt_tth_is_template(type, isTemplate))) return; + if (!isTemplate) { + zv::Val unordered = pt_type_call(Z_OBJ_P(type), PT_LC("forgetkeyorder"), 0, NULL); + if (UNEXPECTED(unordered.isUndef())) return; + (void) pt_type_traverser_traverse(return_value, traverse, unordered.raw()); + return; + } + } + (void) pt_type_traverser_traverse(return_value, traverse, type); +} + } // namespace phpstanturbo using phpstanturbo::TemplateTypeHelper; diff --git a/turbo-ext/src/TypeTraits.cpp b/turbo-ext/src/TypeTraits.cpp index 414ee4a9859..37a6b1f84cb 100644 --- a/turbo-ext/src/TypeTraits.cpp +++ b/turbo-ext/src/TypeTraits.cpp @@ -3931,20 +3931,6 @@ static void ZEND_FASTCALL lrDelegate(INTERNAL_FUNCTION_PARAMETERS) PT_RETURN_VAL(PT_LR_THIS.delegateNamed(fn->common.function_name, argc, argc > 0 ? ZEND_CALL_ARG(execute_data, 1) : NULL)); } -/* getFirstIterableKeyType() / getLastIterableKeyType(): $this->getDelegate()->getIterableKeyType() */ -static void ZEND_FASTCALL lrIterableKeyType(INTERNAL_FUNCTION_PARAMETERS) -{ - ZEND_PARSE_PARAMETERS_NONE(); - PT_RETURN_VAL(PT_LR_THIS.delegate(PT_LC("getiterablekeytype"), 0, NULL)); -} - -/* getFirstIterableValueType() / getLastIterableValueType(): $this->getDelegate()->getIterableValueType() */ -static void ZEND_FASTCALL lrIterableValueType(INTERNAL_FUNCTION_PARAMETERS) -{ - ZEND_PARSE_PARAMETERS_NONE(); - PT_RETURN_VAL(PT_LR_THIS.delegate(PT_LC("getiterablevaluetype"), 0, NULL)); -} - static void ZEND_FASTCALL lrIsSuperTypeOfDefault(INTERNAL_FUNCTION_PARAMETERS) { zval *type; @@ -4012,11 +3998,11 @@ void pt_type_trait_delegating(reg::Class &cls) cls.traitMethod(sigs::isIterableAtLeastOnce, lrDelegate); cls.traitMethod(sigs::getArraySize, lrDelegate); cls.traitMethod(sigs::getIterableKeyType, lrDelegate); - cls.traitMethod(sigs::getFirstIterableKeyType, lrIterableKeyType); - cls.traitMethod(sigs::getLastIterableKeyType, lrIterableKeyType); + cls.traitMethod(sigs::getFirstIterableKeyType, lrDelegate); + cls.traitMethod(sigs::getLastIterableKeyType, lrDelegate); cls.traitMethod(sigs::getIterableValueType, lrDelegate); - cls.traitMethod(sigs::getFirstIterableValueType, lrIterableValueType); - cls.traitMethod(sigs::getLastIterableValueType, lrIterableValueType); + cls.traitMethod(sigs::getFirstIterableValueType, lrDelegate); + cls.traitMethod(sigs::getLastIterableValueType, lrDelegate); cls.traitMethod(sigs::isArray, lrDelegate); cls.traitMethod(sigs::isConstantArray, lrDelegate); cls.traitMethod(sigs::isOversizedArray, lrDelegate); diff --git a/turbo-ext/src/UnionType.cpp b/turbo-ext/src/UnionType.cpp index a995530d634..2c9632363ad 100644 --- a/turbo-ext/src/UnionType.cpp +++ b/turbo-ext/src/UnionType.cpp @@ -1598,6 +1598,10 @@ class UnionType zv::Val fillKeysArray(zval *valueType) const { return unionTypes(UnionMemberOp::call(PT_LC("fillkeysarray"), 1, valueType)); } zv::Val flipArray() const { return unionTypes(UnionMemberOp::call(PT_LC("fliparray"))); } + zv::Val getFirstIterableKeyType() const { return unionTypes(UnionMemberOp::call(PT_LC("getfirstiterablekeytype"))); } + zv::Val getLastIterableKeyType() const { return unionTypes(UnionMemberOp::call(PT_LC("getlastiterablekeytype"))); } + zv::Val getFirstIterableValueType() const { return unionTypes(UnionMemberOp::call(PT_LC("getfirstiterablevaluetype"))); } + zv::Val getLastIterableValueType() const { return unionTypes(UnionMemberOp::call(PT_LC("getlastiterablevaluetype"))); } zv::Val intersectKeyArray(zval *otherArraysType) const { return unionTypes(UnionMemberOp::call(PT_LC("intersectkeyarray"), 1, otherArraysType)); } zv::Val popArray() const { return unionTypes(UnionMemberOp::call(PT_LC("poparray"))); } zv::Val reverseArray(zval *preserveKeys) const { return unionTypes(UnionMemberOp::call(PT_LC("reversearray"), 1, preserveKeys)); } @@ -3400,20 +3404,20 @@ PT_MINIT_REGISTRATION(pt_register_union_type) }); cls.op(); cls.method(sigs::getFirstIterableKeyType, [](INTERNAL_FUNCTION_PARAMETERS) { - pt_ut_value0(INTERNAL_FUNCTION_PARAM_PASSTHRU, &UnionType::getIterableKeyType); + pt_ut_value0(INTERNAL_FUNCTION_PARAM_PASSTHRU, &UnionType::getFirstIterableKeyType); }); cls.method(sigs::getLastIterableKeyType, [](INTERNAL_FUNCTION_PARAMETERS) { - pt_ut_value0(INTERNAL_FUNCTION_PARAM_PASSTHRU, &UnionType::getIterableKeyType); + pt_ut_value0(INTERNAL_FUNCTION_PARAM_PASSTHRU, &UnionType::getLastIterableKeyType); }); cls.method(sigs::getIterableValueType, [](INTERNAL_FUNCTION_PARAMETERS) { pt_ut_value0(INTERNAL_FUNCTION_PARAM_PASSTHRU, &UnionType::getIterableValueType); }); cls.op(); cls.method(sigs::getFirstIterableValueType, [](INTERNAL_FUNCTION_PARAMETERS) { - pt_ut_value0(INTERNAL_FUNCTION_PARAM_PASSTHRU, &UnionType::getIterableValueType); + pt_ut_value0(INTERNAL_FUNCTION_PARAM_PASSTHRU, &UnionType::getFirstIterableValueType); }); cls.method(sigs::getLastIterableValueType, [](INTERNAL_FUNCTION_PARAMETERS) { - pt_ut_value0(INTERNAL_FUNCTION_PARAM_PASSTHRU, &UnionType::getIterableValueType); + pt_ut_value0(INTERNAL_FUNCTION_PARAM_PASSTHRU, &UnionType::getLastIterableValueType); }); cls.method(sigs::isArray, [](INTERNAL_FUNCTION_PARAMETERS) { diff --git a/turbo-ext/src/generated/ConstantArrayType.h b/turbo-ext/src/generated/ConstantArrayType.h index 5a4e9b065fe..6b3b3e5d2ba 100644 --- a/turbo-ext/src/generated/ConstantArrayType.h +++ b/turbo-ext/src/generated/ConstantArrayType.h @@ -26,8 +26,9 @@ inline constexpr uint32_t keyTypes = 12; inline constexpr uint32_t valueTypes = 13; inline constexpr uint32_t nextAutoIndexes = 14; inline constexpr uint32_t optionalKeys = 15; -inline constexpr uint32_t normalizedValueTypes = 16; -inline constexpr uint32_t generalizedTypes = 17; +inline constexpr uint32_t keyOrderKnown = 16; +inline constexpr uint32_t normalizedValueTypes = 17; +inline constexpr uint32_t generalizedTypes = 18; } // namespace slot inline void declareClass(reg::Class &cls) @@ -54,6 +55,7 @@ inline void declareProperties(reg::Class &cls) cls.property("valueTypes", ZEND_ACC_PRIVATE, reg::PropertyKind::Typed, MAY_BE_ARRAY); cls.property("nextAutoIndexes", ZEND_ACC_PRIVATE, reg::PropertyKind::Typed, MAY_BE_ARRAY); cls.property("optionalKeys", ZEND_ACC_PRIVATE, reg::PropertyKind::Typed, MAY_BE_ARRAY); + cls.property("keyOrderKnown", ZEND_ACC_PRIVATE, reg::PropertyKind::Typed, MAY_BE_BOOL); cls.property("normalizedValueTypes", ZEND_ACC_PRIVATE, reg::PropertyKind::TypedEmptyArray, MAY_BE_ARRAY); cls.property("generalizedTypes", ZEND_ACC_PRIVATE, reg::PropertyKind::TypedEmptyArray, MAY_BE_ARRAY); } @@ -80,176 +82,195 @@ inline constexpr char strings[] = "PHPStan\\TrinaryLogic\0" /* 63 */ "null\0" /* 84 */ "unsealed\0" /* 89 */ - "__construct\0" /* 98 */ - "\0" /* 110 */ - "isSealed\0" /* 111 */ - "isUnsealed\0" /* 120 */ - "getUnsealedTypes\0" /* 131 */ - "getUnsealedDeclaredTypes\0" /* 148 */ - "getUnsealedKeyTemplate\0" /* 173 */ - "PHPStan\\Type\\Constant\\ConstantArrayType\0" /* 196 */ - "dropUnsealedTypes\0" /* 236 */ - "recreate\0" /* 254 */ - "keepUnsealedDeclaration\0" /* 263 */ - "getConstantArrays\0" /* 287 */ - "getReferencedClasses\0" /* 305 */ - "PHPStan\\Type\\Type\0" /* 326 */ - "getIterableKeyType\0" /* 344 */ - "getIterableValueType\0" /* 363 */ - "getKeyTypesUnion\0" /* 384 */ - "getKeyType\0" /* 401 */ - "getItemType\0" /* 412 */ - "isConstantValue\0" /* 424 */ - "getNextAutoIndexes\0" /* 440 */ - "getOptionalKeys\0" /* 459 */ - "getAllArrays\0" /* 475 */ - "in\0" /* 488 */ - "powerSet\0" /* 491 */ - "getKeyTypes\0" /* 500 */ - "getValueTypes\0" /* 512 */ - "i\0" /* 526 */ - "isOptionalKey\0" /* 528 */ - "sortKeys\0" /* 542 */ - "type\0" /* 551 */ - "strictTypes\0" /* 556 */ - "PHPStan\\Type\\AcceptsResult\0" /* 568 */ - "accepts\0" /* 595 */ - "checkOurKeys\0" /* 603 */ - "PHPStan\\Type\\IsSuperTypeOfResult\0" /* 616 */ - "isSuperTypeOf\0" /* 649 */ - "sealedArrayShapesCannotBeIntersectedReason\0" /* 663 */ - "phpVersion\0" /* 706 */ - "PHPStan\\Php\\PhpVersion\0" /* 717 */ - "PHPStan\\Type\\BooleanType\0" /* 740 */ - "looseCompare\0" /* 765 */ - "equals\0" /* 778 */ - "isCallable\0" /* 785 */ - "scope\0" /* 796 */ - "PHPStan\\Reflection\\ClassMemberAccessAnswerer\0" /* 802 */ - "getCallableParametersAcceptors\0" /* 847 */ - "findTypeAndMethodNames\0" /* 878 */ - "hasNonExistentMethod\0" /* 901 */ - "false\0" /* 922 */ - "doFindTypeAndMethodNames\0" /* 928 */ - "offsetType\0" /* 953 */ - "hasOffsetValueType\0" /* 964 */ - "recursiveHasOffsetValueType\0" /* 983 */ - "getOffsetValueType\0" /* 1011 */ - "valueType\0" /* 1030 */ - "unionValues\0" /* 1040 */ - "true\0" /* 1052 */ - "setOffsetValueType\0" /* 1057 */ - "setExistingOffsetValueType\0" /* 1076 */ - "preserveListCertainty\0" /* 1103 */ - "unsetOffset\0" /* 1125 */ - "inferIsListFromShape\0" /* 1137 */ - "newKeyTypes\0" /* 1158 */ - "newOptionalKeys\0" /* 1170 */ - "arrayIsList\0" /* 1186 */ - "unsetOptionalKey\0" /* 1198 */ - "isListAfterUnset\0" /* 1215 */ - "lengthType\0" /* 1232 */ - "preserveKeys\0" /* 1243 */ - "chunkArray\0" /* 1256 */ - "fillKeysArray\0" /* 1267 */ - "flipArray\0" /* 1281 */ - "otherArraysType\0" /* 1291 */ - "intersectKeyArray\0" /* 1307 */ - "popArray\0" /* 1325 */ - "reverseArray\0" /* 1334 */ - "needleType\0" /* 1347 */ - "strict\0" /* 1358 */ - "searchArray\0" /* 1365 */ - "shiftArray\0" /* 1377 */ - "shuffleArray\0" /* 1388 */ - "sliceArray\0" /* 1401 */ - "replacementType\0" /* 1412 */ - "spliceArray\0" /* 1428 */ - "sizeType\0" /* 1440 */ - "truncateListToSize\0" /* 1449 */ - "extractTruncateListBounds\0" /* 1468 */ - "isIterableAtLeastOnce\0" /* 1494 */ - "getArraySize\0" /* 1516 */ - "getFirstIterableKeyType\0" /* 1529 */ - "getLastIterableKeyType\0" /* 1553 */ - "getFirstIterableValueType\0" /* 1576 */ - "getLastIterableValueType\0" /* 1602 */ - "isConstantArray\0" /* 1627 */ - "length\0" /* 1643 */ - "removeLastElements\0" /* 1650 */ - "reindex\0" /* 1669 */ - "removeFirstElements\0" /* 1677 */ - "toBoolean\0" /* 1697 */ - "toInteger\0" /* 1707 */ - "toFloat\0" /* 1717 */ - "precision\0" /* 1725 */ - "PHPStan\\Type\\GeneralizePrecision\0" /* 1735 */ - "generalize\0" /* 1768 */ - "doGeneralize\0" /* 1779 */ - "generalizeValues\0" /* 1792 */ - "degradeToGeneralArray\0" /* 1809 */ - "filterValueType\0" /* 1831 */ - "getKeysArrayFiltered\0" /* 1847 */ - "getKeysArray\0" /* 1868 */ - "getValuesArray\0" /* 1881 */ - "types\0" /* 1896 */ - "unsealedSourceType\0" /* 1902 */ - "getKeysOrValuesArray\0" /* 1921 */ - "level\0" /* 1942 */ - "PHPStan\\Type\\VerbosityLevel\0" /* 1948 */ - "describe\0" /* 1976 */ - "shouldBeDescribedAsAList\0" /* 1985 */ - "receivedType\0" /* 2010 */ - "PHPStan\\Type\\Generic\\TemplateTypeMap\0" /* 2023 */ - "inferTemplateTypes\0" /* 2060 */ - "positionVariance\0" /* 2079 */ - "PHPStan\\Type\\Generic\\TemplateTypeVariance\0" /* 2096 */ - "getReferencedTemplateTypes\0" /* 2138 */ - "typeToRemove\0" /* 2165 */ - "tryRemove\0" /* 2178 */ - "removeOffset\0" /* 2188 */ - "cb\0" /* 2201 */ - "traverse\0" /* 2204 */ - "right\0" /* 2213 */ - "traverseSimultaneously\0" /* 2219 */ - "otherArray\0" /* 2242 */ - "isKeysSupersetOf\0" /* 2253 */ - "legacyIsKeysSupersetOf\0" /* 2270 */ - "mergeWith\0" /* 2293 */ - "legacyMergeWith\0" /* 2303 */ - "getKeyIndexMap\0" /* 2319 */ - "findVerifiedKeyIndex\0" /* 2334 */ - "isKeyIndexMiss\0" /* 2355 */ - "other\0" /* 2370 */ - "hasRequiredKeyMissingIn\0" /* 2376 */ - "otherKeyType\0" /* 2400 */ - "getKeyIndex\0" /* 2413 */ - "makeOffsetRequired\0" /* 2425 */ - "makeList\0" /* 2444 */ - "makeListMaybe\0" /* 2453 */ - "mapValueType\0" /* 2467 */ - "mapKeyType\0" /* 2480 */ - "makeAllArrayKeysOptional\0" /* 2491 */ - "case\0" /* 2516 */ - "changeKeyCaseArray\0" /* 2521 */ - "filterArrayRemovingFalsey\0" /* 2540 */ - "PHPStan\\Type\\Constant\\ConstantStringType\0" /* 2566 */ - "foldConstantStringKeyCase\0" /* 2607 */ - "key\0" /* 2633 */ - "foldUnsealedKeyCase\0" /* 2637 */ - "PHPStan\\PhpDocParser\\Ast\\Type\\TypeNode\0" /* 2657 */ - "toPhpDocNode\0" /* 2696 */ - "position\0" /* 2709 */ - "PHPStan\\Type\\NativeTypePosition\0" /* 2718 */ - "toNativePhpTypeNode\0" /* 2750 */ - "value\0" /* 2770 */ - "isValidIdentifier\0" /* 2776 */ - "getFiniteTypes\0" /* 2794 */ - "hasTemplateOrLateResolvableType\0" /* 2809 */ - "hasUnresolvedTemplateArgumentType\0" /* 2841 */ - "otherType\0" /* 2875 */ - "tryUnion\0" /* 2885 */ - "tryIntersect"; /* 2894 */ + "keyOrderKnown\0" /* 98 */ + "true\0" /* 112 */ + "__construct\0" /* 117 */ + "\0" /* 129 */ + "isKeyOrderKnown\0" /* 130 */ + "hasKeyOrderToKeep\0" /* 146 */ + "PHPStan\\Type\\Constant\\ConstantArrayType\0" /* 164 */ + "forgetKeyOrder\0" /* 204 */ + "knowKeyOrder\0" /* 219 */ + "other\0" /* 232 */ + "sharesKeyOrderWith\0" /* 238 */ + "isSealed\0" /* 257 */ + "isUnsealed\0" /* 266 */ + "getUnsealedTypes\0" /* 277 */ + "getUnsealedDeclaredTypes\0" /* 294 */ + "getUnsealedKeyTemplate\0" /* 319 */ + "dropUnsealedTypes\0" /* 342 */ + "recreate\0" /* 360 */ + "keepUnsealedDeclaration\0" /* 369 */ + "getConstantArrays\0" /* 393 */ + "getReferencedClasses\0" /* 411 */ + "PHPStan\\Type\\Type\0" /* 432 */ + "getIterableKeyType\0" /* 450 */ + "getIterableValueType\0" /* 469 */ + "getKeyTypesUnion\0" /* 490 */ + "getKeyType\0" /* 507 */ + "getItemType\0" /* 518 */ + "isConstantValue\0" /* 530 */ + "getNextAutoIndexes\0" /* 546 */ + "getOptionalKeys\0" /* 565 */ + "getAllArrays\0" /* 581 */ + "in\0" /* 594 */ + "powerSet\0" /* 597 */ + "getKeyTypes\0" /* 606 */ + "getValueTypes\0" /* 618 */ + "i\0" /* 632 */ + "isOptionalKey\0" /* 634 */ + "sortKeys\0" /* 648 */ + "shapes\0" /* 657 */ + "inKeyOrderOf\0" /* 664 */ + "indices\0" /* 677 */ + "reorderKeys\0" /* 685 */ + "type\0" /* 697 */ + "strictTypes\0" /* 702 */ + "PHPStan\\Type\\AcceptsResult\0" /* 714 */ + "accepts\0" /* 741 */ + "checkOurKeys\0" /* 749 */ + "PHPStan\\Type\\IsSuperTypeOfResult\0" /* 762 */ + "isSuperTypeOf\0" /* 795 */ + "sealedArrayShapesCannotBeIntersectedReason\0" /* 809 */ + "phpVersion\0" /* 852 */ + "PHPStan\\Php\\PhpVersion\0" /* 863 */ + "PHPStan\\Type\\BooleanType\0" /* 886 */ + "looseCompare\0" /* 911 */ + "equals\0" /* 924 */ + "isCallable\0" /* 931 */ + "scope\0" /* 942 */ + "PHPStan\\Reflection\\ClassMemberAccessAnswerer\0" /* 948 */ + "getCallableParametersAcceptors\0" /* 993 */ + "findTypeAndMethodNames\0" /* 1024 */ + "hasNonExistentMethod\0" /* 1047 */ + "false\0" /* 1068 */ + "doFindTypeAndMethodNames\0" /* 1074 */ + "offsetType\0" /* 1099 */ + "hasOffsetValueType\0" /* 1110 */ + "recursiveHasOffsetValueType\0" /* 1129 */ + "getOffsetValueType\0" /* 1157 */ + "valueType\0" /* 1176 */ + "unionValues\0" /* 1186 */ + "setOffsetValueType\0" /* 1198 */ + "setExistingOffsetValueType\0" /* 1217 */ + "preserveListCertainty\0" /* 1244 */ + "unsetOffset\0" /* 1266 */ + "inferIsListFromShape\0" /* 1278 */ + "newKeyTypes\0" /* 1299 */ + "newOptionalKeys\0" /* 1311 */ + "arrayIsList\0" /* 1327 */ + "unsetOptionalKey\0" /* 1339 */ + "isListAfterUnset\0" /* 1356 */ + "lengthType\0" /* 1373 */ + "preserveKeys\0" /* 1384 */ + "chunkArray\0" /* 1397 */ + "fillKeysArray\0" /* 1408 */ + "flipArray\0" /* 1422 */ + "otherArraysType\0" /* 1432 */ + "intersectKeyArray\0" /* 1448 */ + "popArray\0" /* 1466 */ + "reverseArray\0" /* 1475 */ + "needleType\0" /* 1488 */ + "strict\0" /* 1499 */ + "searchArray\0" /* 1506 */ + "shiftArray\0" /* 1518 */ + "shuffleArray\0" /* 1529 */ + "sliceArray\0" /* 1542 */ + "replacementType\0" /* 1553 */ + "spliceArray\0" /* 1569 */ + "sizeType\0" /* 1581 */ + "truncateListToSize\0" /* 1590 */ + "extractTruncateListBounds\0" /* 1609 */ + "isIterableAtLeastOnce\0" /* 1635 */ + "getArraySize\0" /* 1657 */ + "getFirstIterableKeyType\0" /* 1670 */ + "getLastIterableKeyType\0" /* 1694 */ + "getFirstIterableValueType\0" /* 1717 */ + "getLastIterableValueType\0" /* 1743 */ + "isConstantArray\0" /* 1768 */ + "length\0" /* 1784 */ + "removeLastElements\0" /* 1791 */ + "reindex\0" /* 1810 */ + "removeFirstElements\0" /* 1818 */ + "toBoolean\0" /* 1838 */ + "toInteger\0" /* 1848 */ + "toFloat\0" /* 1858 */ + "precision\0" /* 1866 */ + "PHPStan\\Type\\GeneralizePrecision\0" /* 1876 */ + "generalize\0" /* 1909 */ + "doGeneralize\0" /* 1920 */ + "generalizeValues\0" /* 1933 */ + "degradeToGeneralArray\0" /* 1950 */ + "filterValueType\0" /* 1972 */ + "getKeysArrayFiltered\0" /* 1988 */ + "getKeysArray\0" /* 2009 */ + "getValuesArray\0" /* 2022 */ + "getValuesInKeyOrder\0" /* 2037 */ + "inRenumberingOrder\0" /* 2057 */ + "listsIntegerKey\0" /* 2076 */ + "withoutPositionsOfKeys\0" /* 2092 */ + "types\0" /* 2115 */ + "unsealedSourceType\0" /* 2121 */ + "getKeysOrValuesArray\0" /* 2140 */ + "level\0" /* 2161 */ + "PHPStan\\Type\\VerbosityLevel\0" /* 2167 */ + "describe\0" /* 2195 */ + "namingKeys\0" /* 2204 */ + "shouldBeDescribedAsAList\0" /* 2215 */ + "receivedType\0" /* 2240 */ + "PHPStan\\Type\\Generic\\TemplateTypeMap\0" /* 2253 */ + "inferTemplateTypes\0" /* 2290 */ + "positionVariance\0" /* 2309 */ + "PHPStan\\Type\\Generic\\TemplateTypeVariance\0" /* 2326 */ + "getReferencedTemplateTypes\0" /* 2368 */ + "typeToRemove\0" /* 2395 */ + "tryRemove\0" /* 2408 */ + "removeOffset\0" /* 2418 */ + "cb\0" /* 2431 */ + "traverse\0" /* 2434 */ + "right\0" /* 2443 */ + "traverseSimultaneously\0" /* 2449 */ + "otherArray\0" /* 2472 */ + "isKeysSupersetOf\0" /* 2483 */ + "legacyIsKeysSupersetOf\0" /* 2500 */ + "mergeWith\0" /* 2523 */ + "a\0" /* 2533 */ + "b\0" /* 2535 */ + "inMergedKeyOrderOf\0" /* 2537 */ + "getKeyTypesInMergedOrderWith\0" /* 2556 */ + "legacyMergeWith\0" /* 2585 */ + "getKeyIndexMap\0" /* 2601 */ + "findVerifiedKeyIndex\0" /* 2616 */ + "isKeyIndexMiss\0" /* 2637 */ + "hasRequiredKeyMissingIn\0" /* 2652 */ + "otherKeyType\0" /* 2676 */ + "getKeyIndex\0" /* 2689 */ + "makeOffsetRequired\0" /* 2701 */ + "makeList\0" /* 2720 */ + "makeListMaybe\0" /* 2729 */ + "mapValueType\0" /* 2743 */ + "mapKeyType\0" /* 2756 */ + "makeAllArrayKeysOptional\0" /* 2767 */ + "case\0" /* 2792 */ + "changeKeyCaseArray\0" /* 2797 */ + "filterArrayRemovingFalsey\0" /* 2816 */ + "PHPStan\\Type\\Constant\\ConstantStringType\0" /* 2842 */ + "foldConstantStringKeyCase\0" /* 2883 */ + "key\0" /* 2909 */ + "foldUnsealedKeyCase\0" /* 2913 */ + "PHPStan\\PhpDocParser\\Ast\\Type\\TypeNode\0" /* 2933 */ + "toPhpDocNode\0" /* 2972 */ + "position\0" /* 2985 */ + "PHPStan\\Type\\NativeTypePosition\0" /* 2994 */ + "toNativePhpTypeNode\0" /* 3026 */ + "value\0" /* 3046 */ + "isValidIdentifier\0" /* 3052 */ + "getFiniteTypes\0" /* 3070 */ + "hasTemplateOrLateResolvableType\0" /* 3085 */ + "hasUnresolvedTemplateArgumentType\0" /* 3117 */ + "otherType\0" /* 3151 */ + "tryUnion\0" /* 3161 */ + "tryIntersect"; /* 3170 */ inline constexpr reg::PackedArg args[] = { reg::packed(0, MAY_BE_ARRAY), /* __construct $keyTypes */ reg::packed(9, MAY_BE_ARRAY), /* __construct $valueTypes */ @@ -257,322 +278,356 @@ inline constexpr reg::PackedArg args[] = { reg::packed(40, MAY_BE_ARRAY, reg::NoString, false, false, 53), /* __construct $optionalKeys */ reg::packed(56, MAY_BE_NULL, 63, false, false, 84), /* __construct $isList */ reg::packed(89, MAY_BE_NULL | MAY_BE_ARRAY, reg::NoString, false, false, 84), /* __construct $unsealed */ - reg::packed(110, 0, 63), /* isSealed return */ - reg::packed(110, 0, 63), /* isUnsealed return */ - reg::packed(110, MAY_BE_NULL | MAY_BE_ARRAY), /* getUnsealedTypes return */ - reg::packed(110, MAY_BE_NULL | MAY_BE_ARRAY), /* getUnsealedDeclaredTypes return */ - reg::packed(110, MAY_BE_NULL | MAY_BE_ARRAY), /* getUnsealedKeyTemplate return */ - reg::packed(110, 0, 196), /* dropUnsealedTypes return */ + reg::packed(98, MAY_BE_BOOL, reg::NoString, false, false, 112), /* __construct $keyOrderKnown */ + reg::packed(129, MAY_BE_BOOL), /* isKeyOrderKnown return */ + reg::packed(129, MAY_BE_BOOL), /* hasKeyOrderToKeep return */ + reg::packed(129, 0, 164), /* forgetKeyOrder return */ + reg::packed(129, 0, 164), /* knowKeyOrder return */ + reg::packed(232, 0, 164), /* sharesKeyOrderWith $other */ + reg::packed(129, MAY_BE_BOOL), /* sharesKeyOrderWith return */ + reg::packed(129, 0, 63), /* isSealed return */ + reg::packed(129, 0, 63), /* isUnsealed return */ + reg::packed(129, MAY_BE_NULL | MAY_BE_ARRAY), /* getUnsealedTypes return */ + reg::packed(129, MAY_BE_NULL | MAY_BE_ARRAY), /* getUnsealedDeclaredTypes return */ + reg::packed(129, MAY_BE_NULL | MAY_BE_ARRAY), /* getUnsealedKeyTemplate return */ + reg::packed(129, 0, 164), /* dropUnsealedTypes return */ reg::packed(0, MAY_BE_ARRAY), /* recreate $keyTypes */ reg::packed(9, MAY_BE_ARRAY), /* recreate $valueTypes */ reg::packed(20, MAY_BE_ARRAY), /* recreate $nextAutoIndexes */ reg::packed(40, MAY_BE_ARRAY), /* recreate $optionalKeys */ reg::packed(56, MAY_BE_NULL, 63), /* recreate $isList */ reg::packed(89, MAY_BE_NULL | MAY_BE_ARRAY), /* recreate $unsealed */ - reg::packed(110, 0, 196), /* recreate return */ + reg::packed(129, 0, 164), /* recreate return */ reg::packed(89, MAY_BE_NULL | MAY_BE_ARRAY), /* keepUnsealedDeclaration $unsealed */ - reg::packed(110, MAY_BE_NULL | MAY_BE_ARRAY), /* keepUnsealedDeclaration return */ - reg::packed(110, MAY_BE_ARRAY), /* getConstantArrays return */ - reg::packed(110, MAY_BE_ARRAY), /* getReferencedClasses return */ - reg::packed(110, 0, 326), /* getIterableKeyType return */ - reg::packed(110, 0, 326), /* getIterableValueType return */ - reg::packed(110, 0, 326), /* getKeyTypesUnion return */ - reg::packed(110, 0, 326), /* getKeyType return */ - reg::packed(110, 0, 326), /* getItemType return */ - reg::packed(110, 0, 63), /* isConstantValue return */ - reg::packed(110, MAY_BE_ARRAY), /* getNextAutoIndexes return */ - reg::packed(110, MAY_BE_ARRAY), /* getOptionalKeys return */ - reg::packed(110, MAY_BE_ARRAY), /* getAllArrays return */ - reg::packed(488, MAY_BE_ARRAY), /* powerSet $in */ - reg::packed(110, MAY_BE_ARRAY), /* powerSet return */ - reg::packed(110, MAY_BE_ARRAY), /* getKeyTypes return */ - reg::packed(110, MAY_BE_ARRAY), /* getValueTypes return */ - reg::packed(526, MAY_BE_LONG), /* isOptionalKey $i */ - reg::packed(110, MAY_BE_BOOL), /* isOptionalKey return */ - reg::packed(110, 0, 196), /* sortKeys return */ - reg::packed(551, 0, 326), /* accepts $type */ - reg::packed(556, MAY_BE_BOOL), /* accepts $strictTypes */ - reg::packed(110, 0, 568), /* accepts return */ - reg::packed(551, 0, 326), /* checkOurKeys $type */ - reg::packed(556, MAY_BE_BOOL), /* checkOurKeys $strictTypes */ - reg::packed(110, 0, 568), /* checkOurKeys return */ - reg::packed(551, 0, 326), /* isSuperTypeOf $type */ - reg::packed(110, 0, 616), /* isSuperTypeOf return */ - reg::packed(551, 0, 196), /* sealedArrayShapesCannotBeIntersectedReason $type */ - reg::packed(110, MAY_BE_STRING), /* sealedArrayShapesCannotBeIntersectedReason return */ - reg::packed(551, 0, 326), /* looseCompare $type */ - reg::packed(706, 0, 717), /* looseCompare $phpVersion */ - reg::packed(110, 0, 740), /* looseCompare return */ - reg::packed(551, 0, 326), /* equals $type */ - reg::packed(110, MAY_BE_BOOL), /* equals return */ - reg::packed(110, 0, 63), /* isCallable return */ - reg::packed(796, 0, 802), /* getCallableParametersAcceptors $scope */ - reg::packed(110, MAY_BE_ARRAY), /* getCallableParametersAcceptors return */ - reg::packed(110, MAY_BE_ARRAY), /* findTypeAndMethodNames return */ - reg::packed(901, MAY_BE_BOOL, reg::NoString, true, false, 922), /* doFindTypeAndMethodNames $hasNonExistentMethod */ - reg::packed(110, MAY_BE_ARRAY), /* doFindTypeAndMethodNames return */ - reg::packed(953, 0, 326), /* hasOffsetValueType $offsetType */ - reg::packed(110, 0, 63), /* hasOffsetValueType return */ - reg::packed(953, 0, 326), /* recursiveHasOffsetValueType $offsetType */ - reg::packed(110, 0, 63), /* recursiveHasOffsetValueType return */ - reg::packed(953, 0, 326), /* getOffsetValueType $offsetType */ - reg::packed(110, 0, 326), /* getOffsetValueType return */ - reg::packed(953, MAY_BE_NULL, 326), /* setOffsetValueType $offsetType */ - reg::packed(1030, 0, 326), /* setOffsetValueType $valueType */ - reg::packed(1040, MAY_BE_BOOL, reg::NoString, false, false, 1052), /* setOffsetValueType $unionValues */ - reg::packed(110, 0, 326), /* setOffsetValueType return */ - reg::packed(953, 0, 326), /* setExistingOffsetValueType $offsetType */ - reg::packed(1030, 0, 326), /* setExistingOffsetValueType $valueType */ - reg::packed(110, 0, 326), /* setExistingOffsetValueType return */ - reg::packed(953, 0, 326), /* unsetOffset $offsetType */ - reg::packed(1103, MAY_BE_BOOL, reg::NoString, false, false, 922), /* unsetOffset $preserveListCertainty */ - reg::packed(110, 0, 326), /* unsetOffset return */ + reg::packed(129, MAY_BE_NULL | MAY_BE_ARRAY), /* keepUnsealedDeclaration return */ + reg::packed(129, MAY_BE_ARRAY), /* getConstantArrays return */ + reg::packed(129, MAY_BE_ARRAY), /* getReferencedClasses return */ + reg::packed(129, 0, 432), /* getIterableKeyType return */ + reg::packed(129, 0, 432), /* getIterableValueType return */ + reg::packed(129, 0, 432), /* getKeyTypesUnion return */ + reg::packed(129, 0, 432), /* getKeyType return */ + reg::packed(129, 0, 432), /* getItemType return */ + reg::packed(129, 0, 63), /* isConstantValue return */ + reg::packed(129, MAY_BE_ARRAY), /* getNextAutoIndexes return */ + reg::packed(129, MAY_BE_ARRAY), /* getOptionalKeys return */ + reg::packed(129, MAY_BE_ARRAY), /* getAllArrays return */ + reg::packed(594, MAY_BE_ARRAY), /* powerSet $in */ + reg::packed(129, MAY_BE_ARRAY), /* powerSet return */ + reg::packed(129, MAY_BE_ARRAY), /* getKeyTypes return */ + reg::packed(129, MAY_BE_ARRAY), /* getValueTypes return */ + reg::packed(632, MAY_BE_LONG), /* isOptionalKey $i */ + reg::packed(129, MAY_BE_BOOL), /* isOptionalKey return */ + reg::packed(129, 0, 164), /* sortKeys return */ + reg::packed(657, 0, 164, false, true), /* inKeyOrderOf $shapes */ + reg::packed(129, 0, 164), /* inKeyOrderOf return */ + reg::packed(677, MAY_BE_ARRAY), /* reorderKeys $indices */ + reg::packed(129, 0, 164), /* reorderKeys return */ + reg::packed(697, 0, 432), /* accepts $type */ + reg::packed(702, MAY_BE_BOOL), /* accepts $strictTypes */ + reg::packed(129, 0, 714), /* accepts return */ + reg::packed(697, 0, 432), /* checkOurKeys $type */ + reg::packed(702, MAY_BE_BOOL), /* checkOurKeys $strictTypes */ + reg::packed(129, 0, 714), /* checkOurKeys return */ + reg::packed(697, 0, 432), /* isSuperTypeOf $type */ + reg::packed(129, 0, 762), /* isSuperTypeOf return */ + reg::packed(697, 0, 164), /* sealedArrayShapesCannotBeIntersectedReason $type */ + reg::packed(129, MAY_BE_STRING), /* sealedArrayShapesCannotBeIntersectedReason return */ + reg::packed(697, 0, 432), /* looseCompare $type */ + reg::packed(852, 0, 863), /* looseCompare $phpVersion */ + reg::packed(129, 0, 886), /* looseCompare return */ + reg::packed(697, 0, 432), /* equals $type */ + reg::packed(129, MAY_BE_BOOL), /* equals return */ + reg::packed(129, 0, 63), /* isCallable return */ + reg::packed(942, 0, 948), /* getCallableParametersAcceptors $scope */ + reg::packed(129, MAY_BE_ARRAY), /* getCallableParametersAcceptors return */ + reg::packed(129, MAY_BE_ARRAY), /* findTypeAndMethodNames return */ + reg::packed(1047, MAY_BE_BOOL, reg::NoString, true, false, 1068), /* doFindTypeAndMethodNames $hasNonExistentMethod */ + reg::packed(129, MAY_BE_ARRAY), /* doFindTypeAndMethodNames return */ + reg::packed(1099, 0, 432), /* hasOffsetValueType $offsetType */ + reg::packed(129, 0, 63), /* hasOffsetValueType return */ + reg::packed(1099, 0, 432), /* recursiveHasOffsetValueType $offsetType */ + reg::packed(129, 0, 63), /* recursiveHasOffsetValueType return */ + reg::packed(1099, 0, 432), /* getOffsetValueType $offsetType */ + reg::packed(129, 0, 432), /* getOffsetValueType return */ + reg::packed(1099, MAY_BE_NULL, 432), /* setOffsetValueType $offsetType */ + reg::packed(1176, 0, 432), /* setOffsetValueType $valueType */ + reg::packed(1186, MAY_BE_BOOL, reg::NoString, false, false, 112), /* setOffsetValueType $unionValues */ + reg::packed(129, 0, 432), /* setOffsetValueType return */ + reg::packed(1099, 0, 432), /* setExistingOffsetValueType $offsetType */ + reg::packed(1176, 0, 432), /* setExistingOffsetValueType $valueType */ + reg::packed(129, 0, 432), /* setExistingOffsetValueType return */ + reg::packed(1099, 0, 432), /* unsetOffset $offsetType */ + reg::packed(1244, MAY_BE_BOOL, reg::NoString, false, false, 1068), /* unsetOffset $preserveListCertainty */ + reg::packed(129, 0, 432), /* unsetOffset return */ reg::packed(0, MAY_BE_ARRAY), /* inferIsListFromShape $keyTypes */ reg::packed(40, MAY_BE_ARRAY), /* inferIsListFromShape $optionalKeys */ - reg::packed(110, 0, 63), /* inferIsListFromShape return */ - reg::packed(1158, MAY_BE_ARRAY), /* isListAfterUnset $newKeyTypes */ - reg::packed(1170, MAY_BE_ARRAY), /* isListAfterUnset $newOptionalKeys */ - reg::packed(1186, 0, 63), /* isListAfterUnset $arrayIsList */ - reg::packed(1198, MAY_BE_BOOL), /* isListAfterUnset $unsetOptionalKey */ - reg::packed(110, 0, 63), /* isListAfterUnset return */ - reg::packed(1232, 0, 326), /* chunkArray $lengthType */ - reg::packed(1243, 0, 63), /* chunkArray $preserveKeys */ - reg::packed(110, 0, 326), /* chunkArray return */ - reg::packed(1030, 0, 326), /* fillKeysArray $valueType */ - reg::packed(110, 0, 326), /* fillKeysArray return */ - reg::packed(110, 0, 326), /* flipArray return */ - reg::packed(1291, 0, 326), /* intersectKeyArray $otherArraysType */ - reg::packed(110, 0, 326), /* intersectKeyArray return */ - reg::packed(110, 0, 326), /* popArray return */ - reg::packed(1243, 0, 63), /* reverseArray $preserveKeys */ - reg::packed(110, 0, 326), /* reverseArray return */ - reg::packed(1347, 0, 326), /* searchArray $needleType */ - reg::packed(1358, MAY_BE_NULL, 63, false, false, 84), /* searchArray $strict */ - reg::packed(110, 0, 326), /* searchArray return */ - reg::packed(110, 0, 326), /* shiftArray return */ - reg::packed(110, 0, 326), /* shuffleArray return */ - reg::packed(953, 0, 326), /* sliceArray $offsetType */ - reg::packed(1232, 0, 326), /* sliceArray $lengthType */ - reg::packed(1243, 0, 63), /* sliceArray $preserveKeys */ - reg::packed(110, 0, 326), /* sliceArray return */ - reg::packed(953, 0, 326), /* spliceArray $offsetType */ - reg::packed(1232, 0, 326), /* spliceArray $lengthType */ - reg::packed(1412, 0, 326), /* spliceArray $replacementType */ - reg::packed(110, 0, 326), /* spliceArray return */ - reg::packed(1440, 0, 326), /* truncateListToSize $sizeType */ - reg::packed(110, 0, 326), /* truncateListToSize return */ - reg::packed(1440, 0, 326), /* extractTruncateListBounds $sizeType */ - reg::packed(110, MAY_BE_ARRAY), /* extractTruncateListBounds return */ - reg::packed(110, 0, 63), /* isIterableAtLeastOnce return */ - reg::packed(110, 0, 326), /* getArraySize return */ - reg::packed(110, 0, 326), /* getFirstIterableKeyType return */ - reg::packed(110, 0, 326), /* getLastIterableKeyType return */ - reg::packed(110, 0, 326), /* getFirstIterableValueType return */ - reg::packed(110, 0, 326), /* getLastIterableValueType return */ - reg::packed(110, 0, 63), /* isConstantArray return */ - reg::packed(110, 0, 63), /* isList return */ - reg::packed(1643, MAY_BE_LONG), /* removeLastElements $length */ - reg::packed(110, 0, 196), /* removeLastElements return */ - reg::packed(1643, MAY_BE_LONG), /* removeFirstElements $length */ - reg::packed(1669, MAY_BE_BOOL, reg::NoString, false, false, 1052), /* removeFirstElements $reindex */ - reg::packed(110, 0, 326), /* removeFirstElements return */ - reg::packed(110, 0, 740), /* toBoolean return */ - reg::packed(110, 0, 326), /* toInteger return */ - reg::packed(110, 0, 326), /* toFloat return */ - reg::packed(1725, 0, 1735), /* generalize $precision */ - reg::packed(110, 0, 326), /* generalize return */ - reg::packed(1725, 0, 1735), /* doGeneralize $precision */ - reg::packed(110, 0, 326), /* doGeneralize return */ - reg::packed(110, 0, 196), /* generalizeValues return */ - reg::packed(110, 0, 326), /* degradeToGeneralArray return */ - reg::packed(1831, 0, 326), /* getKeysArrayFiltered $filterValueType */ - reg::packed(1358, 0, 63), /* getKeysArrayFiltered $strict */ - reg::packed(110, 0, 326), /* getKeysArrayFiltered return */ - reg::packed(110, 0, 196), /* getKeysArray return */ - reg::packed(110, 0, 196), /* getValuesArray return */ - reg::packed(1896, MAY_BE_ARRAY), /* getKeysOrValuesArray $types */ - reg::packed(1902, MAY_BE_NULL, 326), /* getKeysOrValuesArray $unsealedSourceType */ - reg::packed(110, 0, 196), /* getKeysOrValuesArray return */ - reg::packed(1942, 0, 1948), /* describe $level */ - reg::packed(110, MAY_BE_STRING), /* describe return */ - reg::packed(110, MAY_BE_BOOL), /* shouldBeDescribedAsAList return */ - reg::packed(2010, 0, 326), /* inferTemplateTypes $receivedType */ - reg::packed(110, 0, 2023), /* inferTemplateTypes return */ - reg::packed(2079, 0, 2096), /* getReferencedTemplateTypes $positionVariance */ - reg::packed(110, MAY_BE_ARRAY), /* getReferencedTemplateTypes return */ - reg::packed(2165, 0, 326), /* tryRemove $typeToRemove */ - reg::packed(110, MAY_BE_NULL, 326), /* tryRemove return */ - reg::packed(953, 0, 326), /* removeOffset $offsetType */ - reg::packed(110, 0, 326), /* removeOffset return */ - reg::packed(2201, MAY_BE_CALLABLE), /* traverse $cb */ - reg::packed(110, 0, 326), /* traverse return */ - reg::packed(2213, 0, 326), /* traverseSimultaneously $right */ - reg::packed(2201, MAY_BE_CALLABLE), /* traverseSimultaneously $cb */ - reg::packed(110, 0, 326), /* traverseSimultaneously return */ - reg::packed(2242, 0, 196), /* isKeysSupersetOf $otherArray */ - reg::packed(110, MAY_BE_BOOL), /* isKeysSupersetOf return */ - reg::packed(2242, 0, 196), /* legacyIsKeysSupersetOf $otherArray */ - reg::packed(110, MAY_BE_BOOL), /* legacyIsKeysSupersetOf return */ - reg::packed(2242, 0, 196), /* mergeWith $otherArray */ - reg::packed(110, 0, 196), /* mergeWith return */ - reg::packed(2242, 0, 196), /* legacyMergeWith $otherArray */ - reg::packed(110, 0, 196), /* legacyMergeWith return */ - reg::packed(110, MAY_BE_ARRAY), /* getKeyIndexMap return */ - reg::packed(953, 0, 326), /* findVerifiedKeyIndex $offsetType */ - reg::packed(110, MAY_BE_NULL | MAY_BE_LONG), /* findVerifiedKeyIndex return */ - reg::packed(953, 0, 326), /* isKeyIndexMiss $offsetType */ - reg::packed(110, MAY_BE_BOOL), /* isKeyIndexMiss return */ - reg::packed(2370, 0, 196), /* hasRequiredKeyMissingIn $other */ - reg::packed(110, MAY_BE_BOOL), /* hasRequiredKeyMissingIn return */ - reg::packed(2400, 0), /* getKeyIndex $otherKeyType */ - reg::packed(110, MAY_BE_NULL | MAY_BE_LONG), /* getKeyIndex return */ - reg::packed(953, 0, 326), /* makeOffsetRequired $offsetType */ - reg::packed(110, 0, 196), /* makeOffsetRequired return */ - reg::packed(110, 0, 326), /* makeList return */ - reg::packed(110, 0, 326), /* makeListMaybe return */ - reg::packed(2201, MAY_BE_CALLABLE), /* mapValueType $cb */ - reg::packed(110, 0, 326), /* mapValueType return */ - reg::packed(2201, MAY_BE_CALLABLE), /* mapKeyType $cb */ - reg::packed(110, 0, 326), /* mapKeyType return */ - reg::packed(110, 0, 326), /* makeAllArrayKeysOptional return */ - reg::packed(2516, MAY_BE_NULL | MAY_BE_LONG), /* changeKeyCaseArray $case */ - reg::packed(110, 0, 326), /* changeKeyCaseArray return */ - reg::packed(110, 0, 326), /* filterArrayRemovingFalsey return */ - reg::packed(551, 0, 2566), /* foldConstantStringKeyCase $type */ - reg::packed(2516, MAY_BE_NULL | MAY_BE_LONG), /* foldConstantStringKeyCase $case */ - reg::packed(110, 0, 326), /* foldConstantStringKeyCase return */ - reg::packed(2633, 0, 326), /* foldUnsealedKeyCase $key */ - reg::packed(2516, MAY_BE_NULL | MAY_BE_LONG), /* foldUnsealedKeyCase $case */ - reg::packed(110, 0, 326), /* foldUnsealedKeyCase return */ - reg::packed(110, 0, 2657), /* toPhpDocNode return */ - reg::packed(2709, 0, 2718), /* toNativePhpTypeNode $position */ - reg::packed(2770, MAY_BE_STRING), /* isValidIdentifier $value */ - reg::packed(110, MAY_BE_BOOL), /* isValidIdentifier return */ - reg::packed(110, MAY_BE_ARRAY), /* getFiniteTypes return */ - reg::packed(110, MAY_BE_BOOL), /* hasTemplateOrLateResolvableType return */ - reg::packed(110, MAY_BE_BOOL), /* hasUnresolvedTemplateArgumentType return */ - reg::packed(2875, 0, 326), /* tryUnion $otherType */ - reg::packed(110, MAY_BE_NULL, 326), /* tryUnion return */ - reg::packed(2875, 0, 326), /* tryIntersect $otherType */ - reg::packed(110, MAY_BE_NULL, 326), /* tryIntersect return */ + reg::packed(129, 0, 63), /* inferIsListFromShape return */ + reg::packed(1299, MAY_BE_ARRAY), /* isListAfterUnset $newKeyTypes */ + reg::packed(1311, MAY_BE_ARRAY), /* isListAfterUnset $newOptionalKeys */ + reg::packed(1327, 0, 63), /* isListAfterUnset $arrayIsList */ + reg::packed(1339, MAY_BE_BOOL), /* isListAfterUnset $unsetOptionalKey */ + reg::packed(129, 0, 63), /* isListAfterUnset return */ + reg::packed(1373, 0, 432), /* chunkArray $lengthType */ + reg::packed(1384, 0, 63), /* chunkArray $preserveKeys */ + reg::packed(129, 0, 432), /* chunkArray return */ + reg::packed(1176, 0, 432), /* fillKeysArray $valueType */ + reg::packed(129, 0, 432), /* fillKeysArray return */ + reg::packed(129, 0, 432), /* flipArray return */ + reg::packed(1432, 0, 432), /* intersectKeyArray $otherArraysType */ + reg::packed(129, 0, 432), /* intersectKeyArray return */ + reg::packed(129, 0, 432), /* popArray return */ + reg::packed(1384, 0, 63), /* reverseArray $preserveKeys */ + reg::packed(129, 0, 432), /* reverseArray return */ + reg::packed(1488, 0, 432), /* searchArray $needleType */ + reg::packed(1499, MAY_BE_NULL, 63, false, false, 84), /* searchArray $strict */ + reg::packed(129, 0, 432), /* searchArray return */ + reg::packed(129, 0, 432), /* shiftArray return */ + reg::packed(129, 0, 432), /* shuffleArray return */ + reg::packed(1099, 0, 432), /* sliceArray $offsetType */ + reg::packed(1373, 0, 432), /* sliceArray $lengthType */ + reg::packed(1384, 0, 63), /* sliceArray $preserveKeys */ + reg::packed(129, 0, 432), /* sliceArray return */ + reg::packed(1099, 0, 432), /* spliceArray $offsetType */ + reg::packed(1373, 0, 432), /* spliceArray $lengthType */ + reg::packed(1553, 0, 432), /* spliceArray $replacementType */ + reg::packed(129, 0, 432), /* spliceArray return */ + reg::packed(1581, 0, 432), /* truncateListToSize $sizeType */ + reg::packed(129, 0, 432), /* truncateListToSize return */ + reg::packed(1581, 0, 432), /* extractTruncateListBounds $sizeType */ + reg::packed(129, MAY_BE_ARRAY), /* extractTruncateListBounds return */ + reg::packed(129, 0, 63), /* isIterableAtLeastOnce return */ + reg::packed(129, 0, 432), /* getArraySize return */ + reg::packed(129, 0, 432), /* getFirstIterableKeyType return */ + reg::packed(129, 0, 432), /* getLastIterableKeyType return */ + reg::packed(129, 0, 432), /* getFirstIterableValueType return */ + reg::packed(129, 0, 432), /* getLastIterableValueType return */ + reg::packed(129, 0, 63), /* isConstantArray return */ + reg::packed(129, 0, 63), /* isList return */ + reg::packed(1784, MAY_BE_LONG), /* removeLastElements $length */ + reg::packed(129, 0, 164), /* removeLastElements return */ + reg::packed(1784, MAY_BE_LONG), /* removeFirstElements $length */ + reg::packed(1810, MAY_BE_BOOL, reg::NoString, false, false, 112), /* removeFirstElements $reindex */ + reg::packed(129, 0, 432), /* removeFirstElements return */ + reg::packed(129, 0, 886), /* toBoolean return */ + reg::packed(129, 0, 432), /* toInteger return */ + reg::packed(129, 0, 432), /* toFloat return */ + reg::packed(1866, 0, 1876), /* generalize $precision */ + reg::packed(129, 0, 432), /* generalize return */ + reg::packed(1866, 0, 1876), /* doGeneralize $precision */ + reg::packed(129, 0, 432), /* doGeneralize return */ + reg::packed(129, 0, 164), /* generalizeValues return */ + reg::packed(129, 0, 432), /* degradeToGeneralArray return */ + reg::packed(1972, 0, 432), /* getKeysArrayFiltered $filterValueType */ + reg::packed(1499, 0, 63), /* getKeysArrayFiltered $strict */ + reg::packed(129, 0, 432), /* getKeysArrayFiltered return */ + reg::packed(129, 0, 164), /* getKeysArray return */ + reg::packed(129, 0, 164), /* getValuesArray return */ + reg::packed(129, 0, 164), /* getValuesInKeyOrder return */ + reg::packed(129, 0, 164), /* inRenumberingOrder return */ + reg::packed(129, MAY_BE_BOOL), /* listsIntegerKey return */ + reg::packed(129, 0, 432), /* withoutPositionsOfKeys return */ + reg::packed(2115, MAY_BE_ARRAY), /* getKeysOrValuesArray $types */ + reg::packed(2121, MAY_BE_NULL, 432), /* getKeysOrValuesArray $unsealedSourceType */ + reg::packed(129, 0, 164), /* getKeysOrValuesArray return */ + reg::packed(2161, 0, 2167), /* describe $level */ + reg::packed(129, MAY_BE_STRING), /* describe return */ + reg::packed(2204, MAY_BE_BOOL, reg::NoString, false, false, 112), /* shouldBeDescribedAsAList $namingKeys */ + reg::packed(129, MAY_BE_BOOL), /* shouldBeDescribedAsAList return */ + reg::packed(2240, 0, 432), /* inferTemplateTypes $receivedType */ + reg::packed(129, 0, 2253), /* inferTemplateTypes return */ + reg::packed(2309, 0, 2326), /* getReferencedTemplateTypes $positionVariance */ + reg::packed(129, MAY_BE_ARRAY), /* getReferencedTemplateTypes return */ + reg::packed(2395, 0, 432), /* tryRemove $typeToRemove */ + reg::packed(129, MAY_BE_NULL, 432), /* tryRemove return */ + reg::packed(1099, 0, 432), /* removeOffset $offsetType */ + reg::packed(129, 0, 432), /* removeOffset return */ + reg::packed(2431, MAY_BE_CALLABLE), /* traverse $cb */ + reg::packed(129, 0, 432), /* traverse return */ + reg::packed(2443, 0, 432), /* traverseSimultaneously $right */ + reg::packed(2431, MAY_BE_CALLABLE), /* traverseSimultaneously $cb */ + reg::packed(129, 0, 432), /* traverseSimultaneously return */ + reg::packed(2472, 0, 164), /* isKeysSupersetOf $otherArray */ + reg::packed(129, MAY_BE_BOOL), /* isKeysSupersetOf return */ + reg::packed(2472, 0, 164), /* legacyIsKeysSupersetOf $otherArray */ + reg::packed(129, MAY_BE_BOOL), /* legacyIsKeysSupersetOf return */ + reg::packed(2472, 0, 164), /* mergeWith $otherArray */ + reg::packed(129, 0, 164), /* mergeWith return */ + reg::packed(2533, 0, 164), /* inMergedKeyOrderOf $a */ + reg::packed(2535, 0, 164), /* inMergedKeyOrderOf $b */ + reg::packed(129, 0, 164), /* inMergedKeyOrderOf return */ + reg::packed(232, 0, 164), /* getKeyTypesInMergedOrderWith $other */ + reg::packed(129, MAY_BE_NULL | MAY_BE_ARRAY), /* getKeyTypesInMergedOrderWith return */ + reg::packed(2472, 0, 164), /* legacyMergeWith $otherArray */ + reg::packed(129, 0, 164), /* legacyMergeWith return */ + reg::packed(129, MAY_BE_ARRAY), /* getKeyIndexMap return */ + reg::packed(1099, 0, 432), /* findVerifiedKeyIndex $offsetType */ + reg::packed(129, MAY_BE_NULL | MAY_BE_LONG), /* findVerifiedKeyIndex return */ + reg::packed(1099, 0, 432), /* isKeyIndexMiss $offsetType */ + reg::packed(129, MAY_BE_BOOL), /* isKeyIndexMiss return */ + reg::packed(232, 0, 164), /* hasRequiredKeyMissingIn $other */ + reg::packed(129, MAY_BE_BOOL), /* hasRequiredKeyMissingIn return */ + reg::packed(2676, 0), /* getKeyIndex $otherKeyType */ + reg::packed(129, MAY_BE_NULL | MAY_BE_LONG), /* getKeyIndex return */ + reg::packed(1099, 0, 432), /* makeOffsetRequired $offsetType */ + reg::packed(129, 0, 164), /* makeOffsetRequired return */ + reg::packed(129, 0, 432), /* makeList return */ + reg::packed(129, 0, 432), /* makeListMaybe return */ + reg::packed(2431, MAY_BE_CALLABLE), /* mapValueType $cb */ + reg::packed(129, 0, 432), /* mapValueType return */ + reg::packed(2431, MAY_BE_CALLABLE), /* mapKeyType $cb */ + reg::packed(129, 0, 432), /* mapKeyType return */ + reg::packed(129, 0, 432), /* makeAllArrayKeysOptional return */ + reg::packed(2792, MAY_BE_NULL | MAY_BE_LONG), /* changeKeyCaseArray $case */ + reg::packed(129, 0, 432), /* changeKeyCaseArray return */ + reg::packed(129, 0, 432), /* filterArrayRemovingFalsey return */ + reg::packed(697, 0, 2842), /* foldConstantStringKeyCase $type */ + reg::packed(2792, MAY_BE_NULL | MAY_BE_LONG), /* foldConstantStringKeyCase $case */ + reg::packed(129, 0, 432), /* foldConstantStringKeyCase return */ + reg::packed(2909, 0, 432), /* foldUnsealedKeyCase $key */ + reg::packed(2792, MAY_BE_NULL | MAY_BE_LONG), /* foldUnsealedKeyCase $case */ + reg::packed(129, 0, 432), /* foldUnsealedKeyCase return */ + reg::packed(129, 0, 2933), /* toPhpDocNode return */ + reg::packed(2985, 0, 2994), /* toNativePhpTypeNode $position */ + reg::packed(3046, MAY_BE_STRING), /* isValidIdentifier $value */ + reg::packed(129, MAY_BE_BOOL), /* isValidIdentifier return */ + reg::packed(129, MAY_BE_ARRAY), /* getFiniteTypes return */ + reg::packed(129, MAY_BE_BOOL), /* hasTemplateOrLateResolvableType return */ + reg::packed(129, MAY_BE_BOOL), /* hasUnresolvedTemplateArgumentType return */ + reg::packed(3151, 0, 432), /* tryUnion $otherType */ + reg::packed(129, MAY_BE_NULL, 432), /* tryUnion return */ + reg::packed(3151, 0, 432), /* tryIntersect $otherType */ + reg::packed(129, MAY_BE_NULL, 432), /* tryIntersect return */ }; using Sig = reg::Sig; } // namespace sigtab /* the signatures of the methods the class declares itself (a used trait's are in the trait's header) */ namespace sig { -inline constexpr sigtab::Sig __construct = { { 98 /* __construct */, 2, 0, 6, reg::NoArg, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig isSealed = { { 111 /* isSealed */, 0, 6, 0, 6, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig isUnsealed = { { 120 /* isUnsealed */, 0, 7, 0, 7, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getUnsealedTypes = { { 131 /* getUnsealedTypes */, 0, 8, 0, 8, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getUnsealedDeclaredTypes = { { 148 /* getUnsealedDeclaredTypes */, 0, 9, 0, 9, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getUnsealedKeyTemplate = { { 173 /* getUnsealedKeyTemplate */, 0, 10, 0, 10, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig dropUnsealedTypes = { { 236 /* dropUnsealedTypes */, 0, 11, 0, 11, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig recreate = { { 254 /* recreate */, 6, 12, 6, 18, ZEND_ACC_PROTECTED } }; -inline constexpr sigtab::Sig keepUnsealedDeclaration = { { 263 /* keepUnsealedDeclaration */, 1, 19, 1, 20, ZEND_ACC_PROTECTED } }; -inline constexpr sigtab::Sig getConstantArrays = { { 287 /* getConstantArrays */, 0, 21, 0, 21, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getReferencedClasses = { { 305 /* getReferencedClasses */, 0, 22, 0, 22, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getIterableKeyType = { { 344 /* getIterableKeyType */, 0, 23, 0, 23, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getIterableValueType = { { 363 /* getIterableValueType */, 0, 24, 0, 24, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getKeyTypesUnion = { { 384 /* getKeyTypesUnion */, 0, 25, 0, 25, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig getKeyType = { { 401 /* getKeyType */, 0, 26, 0, 26, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getItemType = { { 412 /* getItemType */, 0, 27, 0, 27, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig isConstantValue = { { 424 /* isConstantValue */, 0, 28, 0, 28, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getNextAutoIndexes = { { 440 /* getNextAutoIndexes */, 0, 29, 0, 29, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getOptionalKeys = { { 459 /* getOptionalKeys */, 0, 30, 0, 30, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getAllArrays = { { 475 /* getAllArrays */, 0, 31, 0, 31, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig powerSet = { { 491 /* powerSet */, 1, 32, 1, 33, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig getKeyTypes = { { 500 /* getKeyTypes */, 0, 34, 0, 34, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getValueTypes = { { 512 /* getValueTypes */, 0, 35, 0, 35, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig isOptionalKey = { { 528 /* isOptionalKey */, 1, 36, 1, 37, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig sortKeys = { { 542 /* sortKeys */, 0, 38, 0, 38, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig accepts = { { 595 /* accepts */, 2, 39, 2, 41, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig checkOurKeys = { { 603 /* checkOurKeys */, 2, 42, 2, 44, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig isSuperTypeOf = { { 649 /* isSuperTypeOf */, 1, 45, 1, 46, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig sealedArrayShapesCannotBeIntersectedReason = { { 663 /* sealedArrayShapesCannotBeIntersectedReason */, 1, 47, 1, 48, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig looseCompare = { { 765 /* looseCompare */, 2, 49, 2, 51, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig equals = { { 778 /* equals */, 1, 52, 1, 53, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig isCallable = { { 785 /* isCallable */, 0, 54, 0, 54, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getCallableParametersAcceptors = { { 847 /* getCallableParametersAcceptors */, 1, 55, 1, 56, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig findTypeAndMethodNames = { { 878 /* findTypeAndMethodNames */, 0, 57, 0, 57, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig doFindTypeAndMethodNames = { { 928 /* doFindTypeAndMethodNames */, 0, 58, 1, 59, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig hasOffsetValueType = { { 964 /* hasOffsetValueType */, 1, 60, 1, 61, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig recursiveHasOffsetValueType = { { 983 /* recursiveHasOffsetValueType */, 1, 62, 1, 63, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig getOffsetValueType = { { 1011 /* getOffsetValueType */, 1, 64, 1, 65, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig setOffsetValueType = { { 1057 /* setOffsetValueType */, 2, 66, 3, 69, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig setExistingOffsetValueType = { { 1076 /* setExistingOffsetValueType */, 2, 70, 2, 72, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig unsetOffset = { { 1125 /* unsetOffset */, 1, 73, 2, 75, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig inferIsListFromShape = { { 1137 /* inferIsListFromShape */, 2, 76, 2, 78, ZEND_ACC_PRIVATE | ZEND_ACC_STATIC } }; -inline constexpr sigtab::Sig isListAfterUnset = { { 1215 /* isListAfterUnset */, 4, 79, 4, 83, ZEND_ACC_PRIVATE | ZEND_ACC_STATIC } }; -inline constexpr sigtab::Sig chunkArray = { { 1256 /* chunkArray */, 2, 84, 2, 86, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig fillKeysArray = { { 1267 /* fillKeysArray */, 1, 87, 1, 88, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig flipArray = { { 1281 /* flipArray */, 0, 89, 0, 89, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig intersectKeyArray = { { 1307 /* intersectKeyArray */, 1, 90, 1, 91, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig popArray = { { 1325 /* popArray */, 0, 92, 0, 92, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig reverseArray = { { 1334 /* reverseArray */, 1, 93, 1, 94, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig searchArray = { { 1365 /* searchArray */, 1, 95, 2, 97, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig shiftArray = { { 1377 /* shiftArray */, 0, 98, 0, 98, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig shuffleArray = { { 1388 /* shuffleArray */, 0, 99, 0, 99, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig sliceArray = { { 1401 /* sliceArray */, 3, 100, 3, 103, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig spliceArray = { { 1428 /* spliceArray */, 3, 104, 3, 107, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig truncateListToSize = { { 1449 /* truncateListToSize */, 1, 108, 1, 109, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig extractTruncateListBounds = { { 1468 /* extractTruncateListBounds */, 1, 110, 1, 111, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC } }; -inline constexpr sigtab::Sig isIterableAtLeastOnce = { { 1494 /* isIterableAtLeastOnce */, 0, 112, 0, 112, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getArraySize = { { 1516 /* getArraySize */, 0, 113, 0, 113, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getFirstIterableKeyType = { { 1529 /* getFirstIterableKeyType */, 0, 114, 0, 114, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getLastIterableKeyType = { { 1553 /* getLastIterableKeyType */, 0, 115, 0, 115, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getFirstIterableValueType = { { 1576 /* getFirstIterableValueType */, 0, 116, 0, 116, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getLastIterableValueType = { { 1602 /* getLastIterableValueType */, 0, 117, 0, 117, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig isConstantArray = { { 1627 /* isConstantArray */, 0, 118, 0, 118, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig isList = { { 56 /* isList */, 0, 119, 0, 119, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig removeLastElements = { { 1650 /* removeLastElements */, 1, 120, 1, 121, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig removeFirstElements = { { 1677 /* removeFirstElements */, 1, 122, 2, 124, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig toBoolean = { { 1697 /* toBoolean */, 0, 125, 0, 125, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig toInteger = { { 1707 /* toInteger */, 0, 126, 0, 126, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig toFloat = { { 1717 /* toFloat */, 0, 127, 0, 127, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig generalize = { { 1768 /* generalize */, 1, 128, 1, 129, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig doGeneralize = { { 1779 /* doGeneralize */, 1, 130, 1, 131, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig generalizeValues = { { 1792 /* generalizeValues */, 0, 132, 0, 132, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig degradeToGeneralArray = { { 1809 /* degradeToGeneralArray */, 0, 133, 0, 133, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig getKeysArrayFiltered = { { 1847 /* getKeysArrayFiltered */, 2, 134, 2, 136, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getKeysArray = { { 1868 /* getKeysArray */, 0, 137, 0, 137, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getValuesArray = { { 1881 /* getValuesArray */, 0, 138, 0, 138, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getKeysOrValuesArray = { { 1921 /* getKeysOrValuesArray */, 2, 139, 2, 141, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig describe = { { 1976 /* describe */, 1, 142, 1, 143, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig shouldBeDescribedAsAList = { { 1985 /* shouldBeDescribedAsAList */, 0, 144, 0, 144, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig inferTemplateTypes = { { 2060 /* inferTemplateTypes */, 1, 145, 1, 146, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getReferencedTemplateTypes = { { 2138 /* getReferencedTemplateTypes */, 1, 147, 1, 148, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig tryRemove = { { 2178 /* tryRemove */, 1, 149, 1, 150, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig removeOffset = { { 2188 /* removeOffset */, 1, 151, 1, 152, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig traverse = { { 2204 /* traverse */, 1, 153, 1, 154, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig traverseSimultaneously = { { 2219 /* traverseSimultaneously */, 2, 155, 2, 157, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig isKeysSupersetOf = { { 2253 /* isKeysSupersetOf */, 1, 158, 1, 159, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig legacyIsKeysSupersetOf = { { 2270 /* legacyIsKeysSupersetOf */, 1, 160, 1, 161, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig mergeWith = { { 2293 /* mergeWith */, 1, 162, 1, 163, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig legacyMergeWith = { { 2303 /* legacyMergeWith */, 1, 164, 1, 165, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig getKeyIndexMap = { { 2319 /* getKeyIndexMap */, 0, 166, 0, 166, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig findVerifiedKeyIndex = { { 2334 /* findVerifiedKeyIndex */, 1, 167, 1, 168, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig isKeyIndexMiss = { { 2355 /* isKeyIndexMiss */, 1, 169, 1, 170, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig hasRequiredKeyMissingIn = { { 2376 /* hasRequiredKeyMissingIn */, 1, 171, 1, 172, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig getKeyIndex = { { 2413 /* getKeyIndex */, 1, 173, 1, 174, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig makeOffsetRequired = { { 2425 /* makeOffsetRequired */, 1, 175, 1, 176, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig makeList = { { 2444 /* makeList */, 0, 177, 0, 177, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig makeListMaybe = { { 2453 /* makeListMaybe */, 0, 178, 0, 178, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig mapValueType = { { 2467 /* mapValueType */, 1, 179, 1, 180, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig mapKeyType = { { 2480 /* mapKeyType */, 1, 181, 1, 182, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig makeAllArrayKeysOptional = { { 2491 /* makeAllArrayKeysOptional */, 0, 183, 0, 183, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig changeKeyCaseArray = { { 2521 /* changeKeyCaseArray */, 1, 184, 1, 185, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig filterArrayRemovingFalsey = { { 2540 /* filterArrayRemovingFalsey */, 0, 186, 0, 186, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig foldConstantStringKeyCase = { { 2607 /* foldConstantStringKeyCase */, 2, 187, 2, 189, ZEND_ACC_PRIVATE | ZEND_ACC_STATIC } }; -inline constexpr sigtab::Sig foldUnsealedKeyCase = { { 2637 /* foldUnsealedKeyCase */, 2, 190, 2, 192, ZEND_ACC_PRIVATE | ZEND_ACC_STATIC } }; -inline constexpr sigtab::Sig toPhpDocNode = { { 2696 /* toPhpDocNode */, 0, 193, 0, 193, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig toNativePhpTypeNode = { { 2750 /* toNativePhpTypeNode */, 1, 194, 1, reg::NoArg, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig isValidIdentifier = { { 2776 /* isValidIdentifier */, 1, 195, 1, 196, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC } }; -inline constexpr sigtab::Sig getFiniteTypes = { { 2794 /* getFiniteTypes */, 0, 197, 0, 197, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig hasTemplateOrLateResolvableType = { { 2809 /* hasTemplateOrLateResolvableType */, 0, 198, 0, 198, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig hasUnresolvedTemplateArgumentType = { { 2841 /* hasUnresolvedTemplateArgumentType */, 0, 199, 0, 199, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig tryUnion = { { 2885 /* tryUnion */, 1, 200, 1, 201, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig tryIntersect = { { 2894 /* tryIntersect */, 1, 202, 1, 203, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig __construct = { { 117 /* __construct */, 2, 0, 7, reg::NoArg, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig isKeyOrderKnown = { { 130 /* isKeyOrderKnown */, 0, 7, 0, 7, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig hasKeyOrderToKeep = { { 146 /* hasKeyOrderToKeep */, 0, 8, 0, 8, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig forgetKeyOrder = { { 204 /* forgetKeyOrder */, 0, 9, 0, 9, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig knowKeyOrder = { { 219 /* knowKeyOrder */, 0, 10, 0, 10, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig sharesKeyOrderWith = { { 238 /* sharesKeyOrderWith */, 1, 11, 1, 12, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig isSealed = { { 257 /* isSealed */, 0, 13, 0, 13, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig isUnsealed = { { 266 /* isUnsealed */, 0, 14, 0, 14, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getUnsealedTypes = { { 277 /* getUnsealedTypes */, 0, 15, 0, 15, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getUnsealedDeclaredTypes = { { 294 /* getUnsealedDeclaredTypes */, 0, 16, 0, 16, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getUnsealedKeyTemplate = { { 319 /* getUnsealedKeyTemplate */, 0, 17, 0, 17, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig dropUnsealedTypes = { { 342 /* dropUnsealedTypes */, 0, 18, 0, 18, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig recreate = { { 360 /* recreate */, 6, 19, 6, 25, ZEND_ACC_PROTECTED } }; +inline constexpr sigtab::Sig keepUnsealedDeclaration = { { 369 /* keepUnsealedDeclaration */, 1, 26, 1, 27, ZEND_ACC_PROTECTED } }; +inline constexpr sigtab::Sig getConstantArrays = { { 393 /* getConstantArrays */, 0, 28, 0, 28, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getReferencedClasses = { { 411 /* getReferencedClasses */, 0, 29, 0, 29, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getIterableKeyType = { { 450 /* getIterableKeyType */, 0, 30, 0, 30, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getIterableValueType = { { 469 /* getIterableValueType */, 0, 31, 0, 31, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getKeyTypesUnion = { { 490 /* getKeyTypesUnion */, 0, 32, 0, 32, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig getKeyType = { { 507 /* getKeyType */, 0, 33, 0, 33, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getItemType = { { 518 /* getItemType */, 0, 34, 0, 34, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig isConstantValue = { { 530 /* isConstantValue */, 0, 35, 0, 35, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getNextAutoIndexes = { { 546 /* getNextAutoIndexes */, 0, 36, 0, 36, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getOptionalKeys = { { 565 /* getOptionalKeys */, 0, 37, 0, 37, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getAllArrays = { { 581 /* getAllArrays */, 0, 38, 0, 38, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig powerSet = { { 597 /* powerSet */, 1, 39, 1, 40, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig getKeyTypes = { { 606 /* getKeyTypes */, 0, 41, 0, 41, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getValueTypes = { { 618 /* getValueTypes */, 0, 42, 0, 42, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig isOptionalKey = { { 634 /* isOptionalKey */, 1, 43, 1, 44, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig sortKeys = { { 648 /* sortKeys */, 0, 45, 0, 45, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig inKeyOrderOf = { { 664 /* inKeyOrderOf */, 0, 46, 1, 47, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig reorderKeys = { { 685 /* reorderKeys */, 1, 48, 1, 49, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig accepts = { { 741 /* accepts */, 2, 50, 2, 52, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig checkOurKeys = { { 749 /* checkOurKeys */, 2, 53, 2, 55, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig isSuperTypeOf = { { 795 /* isSuperTypeOf */, 1, 56, 1, 57, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig sealedArrayShapesCannotBeIntersectedReason = { { 809 /* sealedArrayShapesCannotBeIntersectedReason */, 1, 58, 1, 59, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig looseCompare = { { 911 /* looseCompare */, 2, 60, 2, 62, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig equals = { { 924 /* equals */, 1, 63, 1, 64, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig isCallable = { { 931 /* isCallable */, 0, 65, 0, 65, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getCallableParametersAcceptors = { { 993 /* getCallableParametersAcceptors */, 1, 66, 1, 67, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig findTypeAndMethodNames = { { 1024 /* findTypeAndMethodNames */, 0, 68, 0, 68, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig doFindTypeAndMethodNames = { { 1074 /* doFindTypeAndMethodNames */, 0, 69, 1, 70, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig hasOffsetValueType = { { 1110 /* hasOffsetValueType */, 1, 71, 1, 72, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig recursiveHasOffsetValueType = { { 1129 /* recursiveHasOffsetValueType */, 1, 73, 1, 74, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig getOffsetValueType = { { 1157 /* getOffsetValueType */, 1, 75, 1, 76, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig setOffsetValueType = { { 1198 /* setOffsetValueType */, 2, 77, 3, 80, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig setExistingOffsetValueType = { { 1217 /* setExistingOffsetValueType */, 2, 81, 2, 83, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig unsetOffset = { { 1266 /* unsetOffset */, 1, 84, 2, 86, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig inferIsListFromShape = { { 1278 /* inferIsListFromShape */, 2, 87, 2, 89, ZEND_ACC_PRIVATE | ZEND_ACC_STATIC } }; +inline constexpr sigtab::Sig isListAfterUnset = { { 1356 /* isListAfterUnset */, 4, 90, 4, 94, ZEND_ACC_PRIVATE | ZEND_ACC_STATIC } }; +inline constexpr sigtab::Sig chunkArray = { { 1397 /* chunkArray */, 2, 95, 2, 97, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig fillKeysArray = { { 1408 /* fillKeysArray */, 1, 98, 1, 99, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig flipArray = { { 1422 /* flipArray */, 0, 100, 0, 100, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig intersectKeyArray = { { 1448 /* intersectKeyArray */, 1, 101, 1, 102, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig popArray = { { 1466 /* popArray */, 0, 103, 0, 103, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig reverseArray = { { 1475 /* reverseArray */, 1, 104, 1, 105, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig searchArray = { { 1506 /* searchArray */, 1, 106, 2, 108, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig shiftArray = { { 1518 /* shiftArray */, 0, 109, 0, 109, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig shuffleArray = { { 1529 /* shuffleArray */, 0, 110, 0, 110, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig sliceArray = { { 1542 /* sliceArray */, 3, 111, 3, 114, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig spliceArray = { { 1569 /* spliceArray */, 3, 115, 3, 118, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig truncateListToSize = { { 1590 /* truncateListToSize */, 1, 119, 1, 120, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig extractTruncateListBounds = { { 1609 /* extractTruncateListBounds */, 1, 121, 1, 122, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC } }; +inline constexpr sigtab::Sig isIterableAtLeastOnce = { { 1635 /* isIterableAtLeastOnce */, 0, 123, 0, 123, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getArraySize = { { 1657 /* getArraySize */, 0, 124, 0, 124, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getFirstIterableKeyType = { { 1670 /* getFirstIterableKeyType */, 0, 125, 0, 125, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getLastIterableKeyType = { { 1694 /* getLastIterableKeyType */, 0, 126, 0, 126, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getFirstIterableValueType = { { 1717 /* getFirstIterableValueType */, 0, 127, 0, 127, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getLastIterableValueType = { { 1743 /* getLastIterableValueType */, 0, 128, 0, 128, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig isConstantArray = { { 1768 /* isConstantArray */, 0, 129, 0, 129, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig isList = { { 56 /* isList */, 0, 130, 0, 130, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig removeLastElements = { { 1791 /* removeLastElements */, 1, 131, 1, 132, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig removeFirstElements = { { 1818 /* removeFirstElements */, 1, 133, 2, 135, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig toBoolean = { { 1838 /* toBoolean */, 0, 136, 0, 136, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig toInteger = { { 1848 /* toInteger */, 0, 137, 0, 137, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig toFloat = { { 1858 /* toFloat */, 0, 138, 0, 138, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig generalize = { { 1909 /* generalize */, 1, 139, 1, 140, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig doGeneralize = { { 1920 /* doGeneralize */, 1, 141, 1, 142, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig generalizeValues = { { 1933 /* generalizeValues */, 0, 143, 0, 143, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig degradeToGeneralArray = { { 1950 /* degradeToGeneralArray */, 0, 144, 0, 144, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig getKeysArrayFiltered = { { 1988 /* getKeysArrayFiltered */, 2, 145, 2, 147, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getKeysArray = { { 2009 /* getKeysArray */, 0, 148, 0, 148, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getValuesArray = { { 2022 /* getValuesArray */, 0, 149, 0, 149, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getValuesInKeyOrder = { { 2037 /* getValuesInKeyOrder */, 0, 150, 0, 150, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig inRenumberingOrder = { { 2057 /* inRenumberingOrder */, 0, 151, 0, 151, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig listsIntegerKey = { { 2076 /* listsIntegerKey */, 0, 152, 0, 152, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig withoutPositionsOfKeys = { { 2092 /* withoutPositionsOfKeys */, 0, 153, 0, 153, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig getKeysOrValuesArray = { { 2140 /* getKeysOrValuesArray */, 2, 154, 2, 156, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig describe = { { 2195 /* describe */, 1, 157, 1, 158, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig shouldBeDescribedAsAList = { { 2215 /* shouldBeDescribedAsAList */, 0, 159, 1, 160, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig inferTemplateTypes = { { 2290 /* inferTemplateTypes */, 1, 161, 1, 162, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getReferencedTemplateTypes = { { 2368 /* getReferencedTemplateTypes */, 1, 163, 1, 164, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig tryRemove = { { 2408 /* tryRemove */, 1, 165, 1, 166, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig removeOffset = { { 2418 /* removeOffset */, 1, 167, 1, 168, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig traverse = { { 2434 /* traverse */, 1, 169, 1, 170, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig traverseSimultaneously = { { 2449 /* traverseSimultaneously */, 2, 171, 2, 173, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig isKeysSupersetOf = { { 2483 /* isKeysSupersetOf */, 1, 174, 1, 175, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig legacyIsKeysSupersetOf = { { 2500 /* legacyIsKeysSupersetOf */, 1, 176, 1, 177, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig mergeWith = { { 2523 /* mergeWith */, 1, 178, 1, 179, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig inMergedKeyOrderOf = { { 2537 /* inMergedKeyOrderOf */, 2, 180, 2, 182, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getKeyTypesInMergedOrderWith = { { 2556 /* getKeyTypesInMergedOrderWith */, 1, 183, 1, 184, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig legacyMergeWith = { { 2585 /* legacyMergeWith */, 1, 185, 1, 186, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig getKeyIndexMap = { { 2601 /* getKeyIndexMap */, 0, 187, 0, 187, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig findVerifiedKeyIndex = { { 2616 /* findVerifiedKeyIndex */, 1, 188, 1, 189, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig isKeyIndexMiss = { { 2637 /* isKeyIndexMiss */, 1, 190, 1, 191, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig hasRequiredKeyMissingIn = { { 2652 /* hasRequiredKeyMissingIn */, 1, 192, 1, 193, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig getKeyIndex = { { 2689 /* getKeyIndex */, 1, 194, 1, 195, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig makeOffsetRequired = { { 2701 /* makeOffsetRequired */, 1, 196, 1, 197, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig makeList = { { 2720 /* makeList */, 0, 198, 0, 198, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig makeListMaybe = { { 2729 /* makeListMaybe */, 0, 199, 0, 199, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig mapValueType = { { 2743 /* mapValueType */, 1, 200, 1, 201, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig mapKeyType = { { 2756 /* mapKeyType */, 1, 202, 1, 203, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig makeAllArrayKeysOptional = { { 2767 /* makeAllArrayKeysOptional */, 0, 204, 0, 204, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig changeKeyCaseArray = { { 2797 /* changeKeyCaseArray */, 1, 205, 1, 206, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig filterArrayRemovingFalsey = { { 2816 /* filterArrayRemovingFalsey */, 0, 207, 0, 207, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig foldConstantStringKeyCase = { { 2883 /* foldConstantStringKeyCase */, 2, 208, 2, 210, ZEND_ACC_PRIVATE | ZEND_ACC_STATIC } }; +inline constexpr sigtab::Sig foldUnsealedKeyCase = { { 2913 /* foldUnsealedKeyCase */, 2, 211, 2, 213, ZEND_ACC_PRIVATE | ZEND_ACC_STATIC } }; +inline constexpr sigtab::Sig toPhpDocNode = { { 2972 /* toPhpDocNode */, 0, 214, 0, 214, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig toNativePhpTypeNode = { { 3026 /* toNativePhpTypeNode */, 1, 215, 1, reg::NoArg, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig isValidIdentifier = { { 3052 /* isValidIdentifier */, 1, 216, 1, 217, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC } }; +inline constexpr sigtab::Sig getFiniteTypes = { { 3070 /* getFiniteTypes */, 0, 218, 0, 218, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig hasTemplateOrLateResolvableType = { { 3085 /* hasTemplateOrLateResolvableType */, 0, 219, 0, 219, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig hasUnresolvedTemplateArgumentType = { { 3117 /* hasUnresolvedTemplateArgumentType */, 0, 220, 0, 220, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig tryUnion = { { 3161 /* tryUnion */, 1, 221, 1, 222, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig tryIntersect = { { 3170 /* tryIntersect */, 1, 223, 1, 224, ZEND_ACC_PUBLIC } }; } // namespace sig } // namespace ptdecl::ConstantArrayType diff --git a/turbo-ext/src/generated/ConstantArrayTypeBuilder.h b/turbo-ext/src/generated/ConstantArrayTypeBuilder.h index 2b42d643eb8..2b5506981fb 100644 --- a/turbo-ext/src/generated/ConstantArrayTypeBuilder.h +++ b/turbo-ext/src/generated/ConstantArrayTypeBuilder.h @@ -15,13 +15,14 @@ inline constexpr uint32_t disableArrayDegradation = 1; inline constexpr uint32_t degradeClosures = 2; inline constexpr uint32_t oversized = 3; inline constexpr uint32_t isNonEmpty = 4; -inline constexpr uint32_t keyTypes = 5; -inline constexpr uint32_t valueTypes = 6; -inline constexpr uint32_t nextAutoIndexes = 7; -inline constexpr uint32_t optionalKeys = 8; -inline constexpr uint32_t isList = 9; -inline constexpr uint32_t unsealed = 10; -inline constexpr uint32_t unsealedDeclaration = 11; +inline constexpr uint32_t keyOrderKnown = 5; +inline constexpr uint32_t keyTypes = 6; +inline constexpr uint32_t valueTypes = 7; +inline constexpr uint32_t nextAutoIndexes = 8; +inline constexpr uint32_t optionalKeys = 9; +inline constexpr uint32_t isList = 10; +inline constexpr uint32_t unsealed = 11; +inline constexpr uint32_t unsealedDeclaration = 12; } // namespace slot inline void declareClass(reg::Class &cls) @@ -37,6 +38,7 @@ inline void declareProperties(reg::Class &cls) cls.property("degradeClosures", ZEND_ACC_PRIVATE, reg::PropertyKind::TypedNull, MAY_BE_NULL | MAY_BE_BOOL); cls.property("oversized", ZEND_ACC_PRIVATE, reg::PropertyKind::TypedBool, 0); cls.property("isNonEmpty", ZEND_ACC_PRIVATE, reg::PropertyKind::Typed, 0, "PHPStan\\TrinaryLogic"); + cls.property("keyOrderKnown", ZEND_ACC_PRIVATE, reg::PropertyKind::TypedBool, 0); cls.property("keyTypes", ZEND_ACC_PRIVATE, reg::PropertyKind::Typed, MAY_BE_ARRAY); cls.property("valueTypes", ZEND_ACC_PRIVATE, reg::PropertyKind::Typed, MAY_BE_ARRAY); cls.property("nextAutoIndexes", ZEND_ACC_PRIVATE, reg::PropertyKind::Typed, MAY_BE_ARRAY); @@ -64,22 +66,26 @@ inline constexpr char strings[] = "startArrayType\0" /* 178 */ "PHPStan\\Type\\Constant\\ConstantArrayType\0" /* 193 */ "createFromConstantArray\0" /* 233 */ - "keyType\0" /* 257 */ - "PHPStan\\Type\\Type\0" /* 265 */ - "valueType\0" /* 283 */ - "makeUnsealed\0" /* 293 */ - "setUnsealed\0" /* 306 */ - "mergeUnsealed\0" /* 318 */ - "offsetType\0" /* 332 */ - "optional\0" /* 343 */ - "false\0" /* 352 */ - "setOffsetValueType\0" /* 358 */ - "markNonListKey\0" /* 377 */ - "oversized\0" /* 392 */ - "degradeToGeneralArray\0" /* 402 */ - "disableClosureDegradation\0" /* 424 */ - "disableArrayDegradation\0" /* 450 */ - "getArray"; /* 474 */ + "makeKeyOrderKnown\0" /* 257 */ + "forgetKeyOrder\0" /* 275 */ + "forgetListKeyOrder\0" /* 290 */ + "keyType\0" /* 309 */ + "PHPStan\\Type\\Type\0" /* 317 */ + "valueType\0" /* 335 */ + "makeUnsealed\0" /* 345 */ + "setUnsealed\0" /* 358 */ + "mergeUnsealed\0" /* 370 */ + "offsetType\0" /* 384 */ + "optional\0" /* 395 */ + "false\0" /* 404 */ + "setOffsetValueType\0" /* 410 */ + "markNonListKey\0" /* 429 */ + "oversized\0" /* 444 */ + "degradeToGeneralArray\0" /* 454 */ + "disableClosureDegradation\0" /* 476 */ + "disableArrayDegradation\0" /* 502 */ + "getArray\0" /* 526 */ + "getListness"; /* 535 */ inline constexpr reg::PackedArg args[] = { reg::packed(0, MAY_BE_ARRAY), /* __construct $keyTypes */ reg::packed(9, MAY_BE_ARRAY), /* __construct $valueTypes */ @@ -91,26 +97,30 @@ inline constexpr reg::PackedArg args[] = { reg::packed(98, 0, 119), /* createEmpty return */ reg::packed(178, 0, 193), /* createFromConstantArray $startArrayType */ reg::packed(98, 0, 119), /* createFromConstantArray return */ - reg::packed(257, 0, 265), /* makeUnsealed $keyType */ - reg::packed(283, 0, 265), /* makeUnsealed $valueType */ + reg::packed(98, MAY_BE_VOID), /* makeKeyOrderKnown return */ + reg::packed(98, MAY_BE_VOID), /* forgetKeyOrder return */ + reg::packed(98, MAY_BE_VOID), /* forgetListKeyOrder return */ + reg::packed(309, 0, 317), /* makeUnsealed $keyType */ + reg::packed(335, 0, 317), /* makeUnsealed $valueType */ reg::packed(98, MAY_BE_VOID), /* makeUnsealed return */ reg::packed(77, MAY_BE_ARRAY), /* setUnsealed $unsealed */ reg::packed(98, MAY_BE_VOID), /* setUnsealed return */ - reg::packed(257, 0, 265), /* mergeUnsealed $keyType */ - reg::packed(283, 0, 265), /* mergeUnsealed $valueType */ + reg::packed(309, 0, 317), /* mergeUnsealed $keyType */ + reg::packed(335, 0, 317), /* mergeUnsealed $valueType */ reg::packed(98, MAY_BE_VOID), /* mergeUnsealed return */ - reg::packed(332, MAY_BE_NULL, 265), /* setOffsetValueType $offsetType */ - reg::packed(283, 0, 265), /* setOffsetValueType $valueType */ - reg::packed(343, MAY_BE_BOOL, reg::NoString, false, false, 352), /* setOffsetValueType $optional */ + reg::packed(384, MAY_BE_NULL, 317), /* setOffsetValueType $offsetType */ + reg::packed(335, 0, 317), /* setOffsetValueType $valueType */ + reg::packed(395, MAY_BE_BOOL, reg::NoString, false, false, 404), /* setOffsetValueType $optional */ reg::packed(98, MAY_BE_VOID), /* setOffsetValueType return */ - reg::packed(343, MAY_BE_BOOL), /* markNonListKey $optional */ + reg::packed(395, MAY_BE_BOOL), /* markNonListKey $optional */ reg::packed(98, MAY_BE_VOID), /* markNonListKey return */ - reg::packed(392, MAY_BE_BOOL, reg::NoString, false, false, 352), /* degradeToGeneralArray $oversized */ + reg::packed(444, MAY_BE_BOOL, reg::NoString, false, false, 404), /* degradeToGeneralArray $oversized */ reg::packed(98, MAY_BE_VOID), /* degradeToGeneralArray return */ reg::packed(98, MAY_BE_VOID), /* disableClosureDegradation return */ reg::packed(98, MAY_BE_VOID), /* disableArrayDegradation return */ - reg::packed(98, 0, 265), /* getArray return */ + reg::packed(98, 0, 317), /* getArray return */ reg::packed(98, MAY_BE_BOOL), /* isList return */ + reg::packed(98, 0, 56), /* getListness return */ }; using Sig = reg::Sig; } // namespace sigtab @@ -121,16 +131,20 @@ inline constexpr sigtab::Sig __construct = { { 86 /* __construct */, 6, 0, 6, re inline constexpr sigtab::Sig getUnsealedForArray = { { 99 /* getUnsealedForArray */, 0, 6, 0, 6, ZEND_ACC_PRIVATE } }; inline constexpr sigtab::Sig createEmpty = { { 166 /* createEmpty */, 0, 7, 0, 7, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC } }; inline constexpr sigtab::Sig createFromConstantArray = { { 233 /* createFromConstantArray */, 1, 8, 1, 9, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC } }; -inline constexpr sigtab::Sig makeUnsealed = { { 293 /* makeUnsealed */, 2, 10, 2, 12, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig setUnsealed = { { 306 /* setUnsealed */, 1, 13, 1, 14, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig mergeUnsealed = { { 318 /* mergeUnsealed */, 2, 15, 2, 17, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig setOffsetValueType = { { 358 /* setOffsetValueType */, 2, 18, 3, 21, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig markNonListKey = { { 377 /* markNonListKey */, 1, 22, 1, 23, ZEND_ACC_PRIVATE } }; -inline constexpr sigtab::Sig degradeToGeneralArray = { { 402 /* degradeToGeneralArray */, 0, 24, 1, 25, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig disableClosureDegradation = { { 424 /* disableClosureDegradation */, 0, 26, 0, 26, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig disableArrayDegradation = { { 450 /* disableArrayDegradation */, 0, 27, 0, 27, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig getArray = { { 474 /* getArray */, 0, 28, 0, 28, ZEND_ACC_PUBLIC } }; -inline constexpr sigtab::Sig isList = { { 49 /* isList */, 0, 29, 0, 29, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig makeKeyOrderKnown = { { 257 /* makeKeyOrderKnown */, 0, 10, 0, 10, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig forgetKeyOrder = { { 275 /* forgetKeyOrder */, 0, 11, 0, 11, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig forgetListKeyOrder = { { 290 /* forgetListKeyOrder */, 0, 12, 0, 12, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig makeUnsealed = { { 345 /* makeUnsealed */, 2, 13, 2, 15, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig setUnsealed = { { 358 /* setUnsealed */, 1, 16, 1, 17, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig mergeUnsealed = { { 370 /* mergeUnsealed */, 2, 18, 2, 20, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig setOffsetValueType = { { 410 /* setOffsetValueType */, 2, 21, 3, 24, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig markNonListKey = { { 429 /* markNonListKey */, 1, 25, 1, 26, ZEND_ACC_PRIVATE } }; +inline constexpr sigtab::Sig degradeToGeneralArray = { { 454 /* degradeToGeneralArray */, 0, 27, 1, 28, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig disableClosureDegradation = { { 476 /* disableClosureDegradation */, 0, 29, 0, 29, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig disableArrayDegradation = { { 502 /* disableArrayDegradation */, 0, 30, 0, 30, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getArray = { { 526 /* getArray */, 0, 31, 0, 31, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig isList = { { 49 /* isList */, 0, 32, 0, 32, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig getListness = { { 535 /* getListness */, 0, 33, 0, 33, ZEND_ACC_PRIVATE } }; } // namespace sig } // namespace ptdecl::ConstantArrayTypeBuilder diff --git a/turbo-ext/src/generated/CountNarrowingHelper.h b/turbo-ext/src/generated/CountNarrowingHelper.h index 42dee400d8f..c31ecc012fe 100644 --- a/turbo-ext/src/generated/CountNarrowingHelper.h +++ b/turbo-ext/src/generated/CountNarrowingHelper.h @@ -50,7 +50,10 @@ inline constexpr char strings[] = "rootExpr\0" /* 349 */ "PhpParser\\Node\\Expr\0" /* 358 */ "PHPStan\\Analyser\\SpecifiedTypes\0" /* 378 */ - "specifyCountSize"; /* 410 */ + "specifyCountSize\0" /* 410 */ + "arrayType\0" /* 427 */ + "PHPStan\\Type\\Constant\\ConstantArrayType\0" /* 437 */ + "narrowShapeToSize"; /* 477 */ inline constexpr reg::PackedArg args[] = { reg::packed(0, 0, 23), /* __construct $defaultNarrowingHelper */ reg::packed(82, 0, 94), /* __construct $exprPrinter */ @@ -65,6 +68,9 @@ inline constexpr reg::PackedArg args[] = { reg::packed(212, 0, 218), /* specifyCountSize $scope */ reg::packed(349, 0, 358), /* specifyCountSize $rootExpr */ reg::packed(249, MAY_BE_NULL, 378), /* specifyCountSize return */ + reg::packed(427, 0, 437), /* narrowShapeToSize $arrayType */ + reg::packed(294, 0, 194), /* narrowShapeToSize $sizeType */ + reg::packed(249, 0, 194), /* narrowShapeToSize return */ }; using Sig = reg::Sig; } // namespace sigtab @@ -74,6 +80,7 @@ namespace sig { inline constexpr sigtab::Sig __construct = { { 127 /* __construct */, 2, 0, 2, reg::NoArg, ZEND_ACC_PUBLIC } }; inline constexpr sigtab::Sig isNormalCountCall = { { 271 /* isNormalCountCall */, 3, 2, 3, 5, ZEND_ACC_PUBLIC } }; inline constexpr sigtab::Sig specifyCountSize = { { 410 /* specifyCountSize */, 6, 6, 6, 12, ZEND_ACC_PUBLIC } }; +inline constexpr sigtab::Sig narrowShapeToSize = { { 477 /* narrowShapeToSize */, 2, 13, 2, 15, ZEND_ACC_PRIVATE } }; } // namespace sig } // namespace ptdecl::CountNarrowingHelper diff --git a/turbo-ext/src/generated/TemplateConstantArrayType.h b/turbo-ext/src/generated/TemplateConstantArrayType.h index 678884bb548..9fd8a2bfda9 100644 --- a/turbo-ext/src/generated/TemplateConstantArrayType.h +++ b/turbo-ext/src/generated/TemplateConstantArrayType.h @@ -10,12 +10,12 @@ namespace ptdecl::TemplateConstantArrayType { /* the OBJ_PROP_NUM slots of the instance properties the class declares (the inherited ones come first) */ namespace slot { -inline constexpr uint32_t name = 18; -inline constexpr uint32_t scope = 19; -inline constexpr uint32_t strategy = 20; -inline constexpr uint32_t variance = 21; -inline constexpr uint32_t bound = 22; -inline constexpr uint32_t default_ = 23; +inline constexpr uint32_t name = 19; +inline constexpr uint32_t scope = 20; +inline constexpr uint32_t strategy = 21; +inline constexpr uint32_t variance = 22; +inline constexpr uint32_t bound = 23; +inline constexpr uint32_t default_ = 24; } // namespace slot inline void declareClass(reg::Class &cls) diff --git a/turbo-ext/src/support.h b/turbo-ext/src/support.h index a732c810987..7fd749a5ef9 100644 --- a/turbo-ext/src/support.h +++ b/turbo-ext/src/support.h @@ -1130,7 +1130,7 @@ extern zend_class_entry *pt_ce_constant_array_type; * shadowing class, the arguments borrowed and checked as the twin's typed * parameters check them; NULL stands for a parameter left at its default; * false = pending exception */ -[[nodiscard]] bool pt_constant_array_type_new(zval *out, zval *keyTypes, zval *valueTypes, zval *nextAutoIndexes = NULL, zval *optionalKeys = NULL, zval *isList = NULL, zval *unsealed = NULL); +[[nodiscard]] bool pt_constant_array_type_new(zval *out, zval *keyTypes, zval *valueTypes, zval *nextAutoIndexes = NULL, zval *optionalKeys = NULL, zval *isList = NULL, zval *unsealed = NULL, bool keyOrderKnown = true); /* ConstantArrayType::isValidIdentifier($value); false = pending exception */ [[nodiscard]] bool pt_constant_array_type_is_valid_identifier(zend_string *value, bool &out); @@ -1494,6 +1494,13 @@ zv::Val pt_constant_array_type_builder_create_from_constant_array(zval *array); * false / UNDEF = pending exception */ [[nodiscard]] bool pt_constant_array_type_builder_set_offset_value_type(zval *builder, zval *offsetType, zval *valueType, bool optional = false); bool pt_constant_array_type_builder_make_unsealed(zval *builder, zval *keyType, zval *valueType); +/* $builder->makeKeyOrderKnown(); false = pending exception */ +[[nodiscard]] bool pt_constant_array_type_builder_make_key_order_known(zval *builder); +/* if ($array->isKeyOrderKnown()) { $builder->makeKeyOrderKnown(); } ($array + * a borrowed ConstantArrayType); false = pending exception */ +[[nodiscard]] bool pt_constant_array_type_builder_keep_key_order_of(zval *builder, zval *array); +/* $builder->forgetKeyOrder(); false = pending exception */ +[[nodiscard]] bool pt_constant_array_type_builder_forget_key_order(zval *builder); [[nodiscard]] bool pt_constant_array_type_builder_merge_unsealed(zval *builder, zval *keyType, zval *valueType); bool pt_constant_array_type_builder_degrade_to_general_array(zval *builder, bool oversized = false); zv::Val pt_constant_array_type_builder_get_array(zval *builder);