Skip to content

Commit 8e89caa

Browse files
committed
Unite entry types for a key template only when an array declares one
ArrayUnion::mergeWithKeyTemplate() united the declared key and value types of every general array before checking whether any of them has a key template. Without one it returned null and mergeIntoGeneralArray() united the same types again, so every merge of general arrays did its union twice - and once more on each nesting level of the values. bug-6948, whose array nests itself fifteen times, no longer finished its benchmark. It now returns before uniting anything when no array declares a key template. Amp-Thread-ID: https://ampcode.com/threads/T-01a1976c-1bde-72f8-b96c-072279109d59
1 parent 6dc37db commit 8e89caa

1 file changed

Lines changed: 15 additions & 4 deletions

File tree

‎src/Type/Combinator/ArrayUnion.php‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -369,7 +369,7 @@ public static function mergeIntoGeneralArray(array $arrayTypes, bool $widen = fa
369369
*/
370370
private static function mergeWithKeyTemplate(array $arrayTypes): ?ArrayType
371371
{
372-
$entryTypes = null;
372+
$generalArrays = [];
373373
$hasKeyTemplate = false;
374374
foreach ($arrayTypes as $arrayType) {
375375
foreach ($arrayType->getConstantArrays() as $constantArray) {
@@ -387,12 +387,23 @@ private static function mergeWithKeyTemplate(array $arrayTypes): ?ArrayType
387387
return null;
388388
}
389389
$hasKeyTemplate = $hasKeyTemplate || $array->getKeyTemplate() !== null;
390-
$declared = $array->getDeclaredTypes();
391-
$entryTypes = $entryTypes === null ? $declared : ArrayKeyTemplateHelper::unionEntryTypes($entryTypes, $declared);
390+
$generalArrays[] = $array;
392391
}
393392
}
394393

395-
if (!$hasKeyTemplate || ArrayKeyTemplateHelper::findTemplate($entryTypes[0]) === null) {
394+
// without a key template, uniting the entry types here would only
395+
// repeat the union the caller makes - for every nesting level of the values
396+
if (!$hasKeyTemplate) {
397+
return null;
398+
}
399+
400+
$entryTypes = null;
401+
foreach ($generalArrays as $array) {
402+
$declared = $array->getDeclaredTypes();
403+
$entryTypes = $entryTypes === null ? $declared : ArrayKeyTemplateHelper::unionEntryTypes($entryTypes, $declared);
404+
}
405+
406+
if (ArrayKeyTemplateHelper::findTemplate($entryTypes[0]) === null) {
396407
return null;
397408
}
398409

0 commit comments

Comments
 (0)