From efc9065a815e3ec87902e6593797c05bca8ee68b Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Fri, 27 Nov 2026 10:43:18 +0000 Subject: [PATCH 1/3] Keep at most AcceptsResult::REASONS_LIMIT reasons Every member of a union that rejects a type adds its own reasons, and ConstantArrayType::checkOurKeys() prefixes each one with the full value types, so the reasons of nested unions of shapes multiply with every level. A recursive mapping type produced 829 reasons and a 2.7 MB tip on a single return.type error. The constructor now keeps only the first ten. Amp-Thread-ID: https://ampcode.com/threads/T-01a21c50-6b52-77f7-9d04-dff937be67fa --- src/Type/AcceptsResult.php | 16 +++++++++++++++- turbo-ext/src/AcceptsResult.cpp | 26 ++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/Type/AcceptsResult.php b/src/Type/AcceptsResult.php index 7e2c00a57c2..b8ae7e362dd 100644 --- a/src/Type/AcceptsResult.php +++ b/src/Type/AcceptsResult.php @@ -6,8 +6,10 @@ use PHPStan\TrinaryLogic; use PHPStan\Turbo\ShadowedByTurboExtension; use function array_merge; +use function array_slice; use function array_unique; use function array_values; +use function count; /** * Result of a Type::accepts() check — whether one type accepts another. @@ -30,6 +32,14 @@ final class AcceptsResult { + /** + * Every member of a union that rejects a type adds its own reasons, so the + * reasons of nested unions multiply with every level they are nested in. + * Only the first ones are kept, which bounds both the work spent building + * them and the tip they end up in. + */ + public const REASONS_LIMIT = 10; + private static self $YES; private static self $MAYBE; @@ -42,11 +52,15 @@ final class AcceptsResult */ public function __construct( public readonly TrinaryLogic $result, - public readonly array $reasons, + array $reasons, ) { + $this->reasons = count($reasons) > self::REASONS_LIMIT ? array_slice($reasons, 0, self::REASONS_LIMIT) : $reasons; } + /** @var list */ + public readonly array $reasons; + /** * @phpstan-assert-if-true =false $this->no() * @phpstan-assert-if-true =false $this->maybe() diff --git a/turbo-ext/src/AcceptsResult.cpp b/turbo-ext/src/AcceptsResult.cpp index b59001b1ba8..e8a3823696a 100644 --- a/turbo-ext/src/AcceptsResult.cpp +++ b/turbo-ext/src/AcceptsResult.cpp @@ -419,6 +419,29 @@ bool pt_reasons_merge_operands(zval *result, zend_object *self, zval *operands, return true; } +/* AcceptsResult::REASONS_LIMIT: the constructor keeps only the first + * reasons, array_slice($reasons, 0, REASONS_LIMIT) — owned is replaced by + * the slice (a packed list, like array_slice() of a list returns) */ +#define PT_ACCEPTS_RESULT_REASONS_LIMIT 10 +static void pt_accepts_result_cap_reasons(zval *owned) +{ + HashTable *ht = Z_ARRVAL_P(owned); + if (EXPECTED(zend_hash_num_elements(ht) <= PT_ACCEPTS_RESULT_REASONS_LIMIT)) return; + zval sliced; + array_init_size(&sliced, PT_ACCEPTS_RESULT_REASONS_LIMIT); + zend_hash_real_init_packed(Z_ARRVAL(sliced)); + uint32_t taken = 0; + zval *value; + ZEND_HASH_FOREACH_VAL(ht, value) { + if (taken == PT_ACCEPTS_RESULT_REASONS_LIMIT) break; + Z_TRY_ADDREF_P(value); + zend_hash_next_index_insert_new(Z_ARRVAL(sliced), value); + taken++; + } ZEND_HASH_FOREACH_END(); + zval_ptr_dtor(owned); + ZVAL_COPY_VALUE(owned, &sliced); +} + /* }}} */ namespace phpstanturbo { @@ -438,6 +461,7 @@ class AcceptsResult ZVAL_COPY(©, result); pt_readonly_slot_init(self, PT_RESULT_PROP_RESULT, ©); ZVAL_COPY(©, reasons); + pt_accepts_result_cap_reasons(©); pt_readonly_slot_init(self, PT_RESULT_PROP_REASONS, ©); return true; } @@ -553,6 +577,7 @@ class AcceptsResult if (UNEXPECTED(ce == NULL)) return zv::Val(); zval out; zval reasonsRaw = reasons.take(); + pt_accepts_result_cap_reasons(&reasonsRaw); if (UNEXPECTED(!pt_result_object_create(&out, ce, trinary, &reasonsRaw, NULL))) return zv::Val(); return zv::Val::adopt(out); } @@ -760,6 +785,7 @@ PT_MINIT_REGISTRATION(pt_register_accepts_result) /* the static flyweight properties stay unused: the natives keep the * singletons in the request globals */ ptdecl::AcceptsResult::declareProperties(cls); + cls.classConstantLong("REASONS_LIMIT", PT_ACCEPTS_RESULT_REASONS_LIMIT); cls.method(sigs::__construct, [](INTERNAL_FUNCTION_PARAMETERS) { zval *result, *reasons; From cb83dee3db51a7a0b2a49c17c620ec7f8bdc8eb0 Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Fri, 27 Nov 2026 10:43:18 +0000 Subject: [PATCH 2/3] Escape non-style tags before formatting messages and tips Symfony's OutputFormatter reads every <...> in a type description such as array as a possible style tag and measures the text up to it from the start of the message, which is quadratic in the message length: a 2.7 MB tip took about 11 minutes to format. ConsoleTagEscaper escapes what is not a style tag before the table and JSON formatters format it, so the escaped tags are skipped. The output stays the same. Amp-Thread-ID: https://ampcode.com/threads/T-01a21c50-6b52-77f7-9d04-dff937be67fa --- .../ErrorFormatter/ConsoleTagEscaper.php | 46 +++++++++++++++++++ .../ErrorFormatter/JsonErrorFormatter.php | 2 +- .../ErrorFormatter/TableErrorFormatter.php | 6 +-- .../ErrorFormatter/JsonErrorFormatterTest.php | 1 + 4 files changed, 51 insertions(+), 4 deletions(-) create mode 100644 src/Command/ErrorFormatter/ConsoleTagEscaper.php diff --git a/src/Command/ErrorFormatter/ConsoleTagEscaper.php b/src/Command/ErrorFormatter/ConsoleTagEscaper.php new file mode 100644 index 00000000000..f73df989d94 --- /dev/null +++ b/src/Command/ErrorFormatter/ConsoleTagEscaper.php @@ -0,0 +1,46 @@ +` in an error message or tip that are not console style tags, + * such as `array` in a type description, keeping `...` + * and the like. Symfony's OutputFormatter prints a tag it cannot parse as it is, + * but before finding out it measures the text up to it from the start of the + * message, which takes time quadratic in the length of messages that describe + * big types. An escaped `\<` is skipped before that measurement. + * + * @internal + */ +final class ConsoleTagEscaper +{ + + private static ?OutputFormatter $formatter = null; + + public static function escape(string $text): string + { + $formatter = self::$formatter ??= new OutputFormatter(); + + return (string) preg_replace_callback( + '~(?]*)>~', + static function (array $matches) use ($formatter): string { + $tag = $matches[2]; + if ( + ($matches[1] === '/' && $tag === '') + || $formatter->hasStyle($tag) + || preg_match('~^(?:(?:fg|bg|options|href)=[^;]+(?:;|$))+$~i', $tag) === 1 + ) { + return $matches[0]; + } + + return '\\<' . $matches[1] . $tag . '\\>'; + }, + $text, + ); + } + +} diff --git a/src/Command/ErrorFormatter/JsonErrorFormatter.php b/src/Command/ErrorFormatter/JsonErrorFormatter.php index eaa19c5494e..c7b0274da7e 100644 --- a/src/Command/ErrorFormatter/JsonErrorFormatter.php +++ b/src/Command/ErrorFormatter/JsonErrorFormatter.php @@ -47,7 +47,7 @@ public function formatErrors(AnalysisResult $analysisResult, Output $output): in ]; if ($fileSpecificError->getTip() !== null) { - $message['tip'] = $tipFormatter->format($fileSpecificError->getTip()); + $message['tip'] = $tipFormatter->format(ConsoleTagEscaper::escape($fileSpecificError->getTip())); } if ($fileSpecificError->getIdentifier() !== null) { diff --git a/src/Command/ErrorFormatter/TableErrorFormatter.php b/src/Command/ErrorFormatter/TableErrorFormatter.php index 508555837e0..a6cd98a5834 100644 --- a/src/Command/ErrorFormatter/TableErrorFormatter.php +++ b/src/Command/ErrorFormatter/TableErrorFormatter.php @@ -113,13 +113,13 @@ public function formatErrors( foreach ($fileErrors as $file => $errors) { $rows = []; foreach ($errors as $error) { - $message = $error->getMessage(); + $message = ConsoleTagEscaper::escape($error->getMessage()); $filePath = $error->getTraitFilePath() ?? $error->getFilePath(); if ( $error->getIdentifier() !== null && in_array($error->getIdentifier(), ['phpstan.type', 'phpstan.nativeType', 'phpstan.variable', 'phpstan.dumpType', 'phpstan.unknownExpectation'], true) ) { - $message = '' . OutputFormatter::escape($message) . ''; + $message = '' . OutputFormatter::escape($error->getMessage()) . ''; } if ($error->getFixedErrorDiffs() !== []) { $message .= ' šŸ”§'; @@ -133,7 +133,7 @@ public function formatErrors( } if ($error->getTip() !== null) { $tip = $error->getTip(); - $tip = str_replace('%configurationFile%', $projectConfigFile, $tip); + $tip = ConsoleTagEscaper::escape(str_replace('%configurationFile%', $projectConfigFile, $tip)); $message .= "\n"; if (str_contains($tip, "\n")) { diff --git a/tests/PHPStan/Command/ErrorFormatter/JsonErrorFormatterTest.php b/tests/PHPStan/Command/ErrorFormatter/JsonErrorFormatterTest.php index da63c9227eb..f587925222d 100644 --- a/tests/PHPStan/Command/ErrorFormatter/JsonErrorFormatterTest.php +++ b/tests/PHPStan/Command/ErrorFormatter/JsonErrorFormatterTest.php @@ -238,6 +238,7 @@ public static function dataFormatTip(): iterable yield ['tip', 'tip']; yield ['%configurationFile%', '%configurationFile%']; yield ['this check by setting treatPhpDocTypesAsCertain: false in your %configurationFile%.', 'this check by setting treatPhpDocTypesAsCertain: false in your %configurationFile%.']; + yield ["Offset 'a' (array>) does not accept type list<\\Foo>.", "Offset 'a' (array>) does not accept type list<\\Foo>."]; } #[DataProvider('dataFormatTip')] From f293069863bc0b433ded4eec4c8f6a57e91f2f26 Mon Sep 17 00:00:00 2001 From: "ondrej@mirtes.cz" Date: Fri, 27 Nov 2026 10:43:18 +0000 Subject: [PATCH 3/3] Accept a merged shape when a union accepts each of the shapes it holds union() merges shapes that differ at one key into one shape, such as array{type: 'boolean'|'keyword'}, which no member of array{type: 'boolean'}|array{type: 'keyword', fields?: ...} accepts alone. UnionType::accepts() now splits such a shape at a key holding a union of constant scalars and accepts it when it accepts every piece. Amp-Thread-ID: https://ampcode.com/threads/T-01a21c50-6b52-77f7-9d04-dff937be67fa --- src/Type/ArrayAlgebra.php | 61 +++++++++++++++++++ src/Type/UnionType.php | 19 ++++++ .../Rules/Methods/ReturnTypeRuleTest.php | 11 ++++ .../Methods/data/accepts-merged-shapes.php | 46 ++++++++++++++ turbo-ext/src/UnionType.cpp | 32 ++++++++++ 5 files changed, 169 insertions(+) create mode 100644 tests/PHPStan/Rules/Methods/data/accepts-merged-shapes.php diff --git a/src/Type/ArrayAlgebra.php b/src/Type/ArrayAlgebra.php index 82cddbef876..5af5e53ef1f 100644 --- a/src/Type/ArrayAlgebra.php +++ b/src/Type/ArrayAlgebra.php @@ -36,6 +36,67 @@ final class ArrayAlgebra /** The most optional keys whose sets tryUnionConstantArrayBesideEmptyArray() counts in an integer. */ private const KEY_SETS_COUNTED_LIMIT = 62; + /** The most shapes splitConstantArrayAtFiniteValue() splits a shape into, over all of its keys. */ + private const SPLIT_SHAPES_LIMIT = 64; + + /** + * The shapes of a shape, one per value of its first key whose value is a + * union of finitely many values: `array{type: 'a'|'b', x: int}` is + * `array{type: 'a', x: int}` and `array{type: 'b', x: int}`. + * + * tryUnionConstantArray() merges shapes that differ at one key into one + * shape, which a union of the shapes it merged no longer accepts member by + * member - UnionType::accepts() splits it back with this. Null when no key + * has such a value, or when the shape splits into more than + * SPLIT_SHAPES_LIMIT shapes over all of its keys. + * + * @return list|null + */ + public static function splitConstantArrayAtFiniteValue(ConstantArrayType $array): ?array + { + $valueTypes = $array->getValueTypes(); + $splitIndex = null; + $splitValues = []; + $shapesCount = 1; + foreach ($valueTypes as $i => $valueType) { + // unions of constant scalars, the values tryUnionConstantArray() unions at one key + if (!$valueType instanceof UnionType || $valueType instanceof TemplateType || !$valueType->isConstantScalarValue()->yes()) { + continue; + } + $finiteTypes = $valueType->getFiniteTypes(); + if (count($finiteTypes) < 2) { + continue; + } + $shapesCount *= count($finiteTypes); + if ($shapesCount > self::SPLIT_SHAPES_LIMIT) { + return null; + } + if ($splitIndex !== null) { + continue; + } + $splitIndex = $i; + $splitValues = $finiteTypes; + } + if ($splitIndex === null) { + return null; + } + + $shapes = []; + foreach ($splitValues as $splitValue) { + $valueTypes[$splitIndex] = $splitValue; + $shapes[] = new ConstantArrayType( + $array->getKeyTypes(), + $valueTypes, + $array->getNextAutoIndexes(), + $array->getOptionalKeys(), + $array->isList(), + $array->getUnsealedTypes(), + ); + } + + return $shapes; + } + /** @see Type::tryIntersect() */ public static function tryIntersectConstantArray(ConstantArrayType $array, Type $otherType): ?Type { diff --git a/src/Type/UnionType.php b/src/Type/UnionType.php index 71760c66cc8..02ed7f4e023 100644 --- a/src/Type/UnionType.php +++ b/src/Type/UnionType.php @@ -325,6 +325,25 @@ public function accepts(Type $type, bool $strictTypes): AcceptsResult return $result; } + // A shape that union() merged from shapes differing at one key is accepted when + // each of the shapes it holds is, even when no single member accepts all of them. + $constantArrays = $type->getConstantArrays(); + if (count($constantArrays) === 1 && !$type instanceof TemplateType && $type->isConstantArray()->yes()) { + $shapes = ArrayAlgebra::splitConstantArrayAtFiniteValue($constantArrays[0]); + if ($shapes !== null) { + $acceptsShapes = true; + foreach ($shapes as $shape) { + if (!$this->accepts($shape, $strictTypes)->yes()) { + $acceptsShapes = false; + break; + } + } + if ($acceptsShapes) { + return AcceptsResult::createYes(); + } + } + } + $commonReasons = null; foreach ($innerAccepts as $innerResult) { if ($commonReasons === null) { diff --git a/tests/PHPStan/Rules/Methods/ReturnTypeRuleTest.php b/tests/PHPStan/Rules/Methods/ReturnTypeRuleTest.php index 7e390c2ac11..dd2eb5a3ea9 100644 --- a/tests/PHPStan/Rules/Methods/ReturnTypeRuleTest.php +++ b/tests/PHPStan/Rules/Methods/ReturnTypeRuleTest.php @@ -1430,4 +1430,15 @@ public function testBug13325(): void $this->analyse([__DIR__ . '/data/bug-13325.php'], []); } + public function testAcceptsMergedShapes(): void + { + $this->analyse([__DIR__ . '/data/accepts-merged-shapes.php'], [ + [ + "Method AcceptsMergedShapes\\Foo::notAccepted() should return array{type: 'boolean', name: string}|array{type: 'date', name: string, format: string}|array{type: 'keyword', name: string, fields?: array>} but returns array{type: 'boolean'|'text', name: string}.", + 43, + "• Type #1 from the union: Offset 'type' ('boolean') does not accept type 'boolean'|'text'.\n• Type #2 from the union: Offset 'type' ('date') does not accept type 'boolean'|'text'.\n• Type #3 from the union: Offset 'type' ('keyword') does not accept type 'boolean'|'text'.", + ], + ]); + } + } diff --git a/tests/PHPStan/Rules/Methods/data/accepts-merged-shapes.php b/tests/PHPStan/Rules/Methods/data/accepts-merged-shapes.php new file mode 100644 index 00000000000..4c4f8cf92e2 --- /dev/null +++ b/tests/PHPStan/Rules/Methods/data/accepts-merged-shapes.php @@ -0,0 +1,46 @@ +>} + * @phpstan-type P PBool|PKeyword|array{type: 'date', name: string, format: string} + * @phpstan-type PObject array{type: 'object', properties: array} + */ +final class Foo +{ + + /** @return P */ + public function merged(bool $b, string $name): array + { + return $b ? ['type' => 'boolean', 'name' => $name] : ['type' => 'keyword', 'name' => $name]; + } + + /** @return array{a: 1, b: 1}|array{a: 2, b: 2}|array{a: 1, b: 2}|array{a: 2, b: 1, c?: int} */ + public function mergedAtTwoKeys(int $i): array + { + return ['a' => $i === 1 ? 1 : 2, 'b' => $i === 3 ? 1 : 2]; + } + + /** + * @param PObject $mapping + * @return PObject + */ + public function nested(array $mapping): array + { + $mapping['properties'] += [ + 'a' => ['type' => 'keyword', 'name' => 'a'], + 'b' => ['type' => 'boolean', 'name' => 'a'], + ]; + + return $mapping; + } + + /** @return P */ + public function notAccepted(bool $b, string $name): array + { + return $b ? ['type' => 'boolean', 'name' => $name] : ['type' => 'text', 'name' => $name]; + } + +} diff --git a/turbo-ext/src/UnionType.cpp b/turbo-ext/src/UnionType.cpp index 55019f37506..3169d0627cc 100644 --- a/turbo-ext/src/UnionType.cpp +++ b/turbo-ext/src/UnionType.cpp @@ -678,6 +678,38 @@ class UnionType if (UNEXPECTED(resultValue < 0)) return zv::Val(); if (resultValue == PT_TRI_YES) return result; + /* a shape union() merged from shapes differing at one key is accepted + * when each of the shapes it holds is: + * ArrayAlgebra::splitConstantArrayAtFiniteValue($constantArrays[0]) of + * a type that is one constant array and no template */ + zv::Val constantArrays = pt_type_call_array(Z_OBJ_P(type), PT_LC("getconstantarrays"), 0, NULL); + if (UNEXPECTED(constantArrays.isUndef())) return zv::Val(); + bool splitIsTemplate = false; + if (zv::ArrRef(constantArrays.raw()).size() == 1 && UNEXPECTED(!isInstance(type, PT_CLASS_TEMPLATE_TYPE, splitIsTemplate))) return zv::Val(); + zend_long splitIsConstantArray = PT_TRI_NO; + if (zv::ArrRef(constantArrays.raw()).size() == 1 && !splitIsTemplate) { + splitIsConstantArray = pt_type_call_trinary(Z_OBJ_P(type), PT_LC("isconstantarray"), 0, NULL); + if (UNEXPECTED(splitIsConstantArray < 0)) return zv::Val(); + } + if (splitIsConstantArray == PT_TRI_YES) { + zval splitArgv[1]; + ZVAL_COPY_VALUE(&splitArgv[0], zend_hash_index_find(Z_ARRVAL_P(constantArrays.raw()), 0)); + zv::Val shapes = pt_type_call_static(PT_CLASS_ARRAY_ALGEBRA, PT_LC("splitconstantarrayatfinitevalue"), 1, splitArgv); + if (UNEXPECTED(shapes.isUndef())) return zv::Val(); + if (!zv::Ref(shapes.raw()).isNull()) { + bool acceptsShapes = true; + for (zv::ArrayEntry shape : zv::ArrRef(shapes.raw())) { + zend_long accepted = acceptsTrinary(thisAccepts(shape.value().deref().raw(), strictTypes)); + if (UNEXPECTED(accepted < 0)) return zv::Val(); + if (accepted != PT_TRI_YES) { + acceptsShapes = false; + break; + } + } + if (acceptsShapes) return acceptsResult(PT_TRI_YES); + } + } + /* the reasons every member shares, decorated per member */ zv::Val commonReasons; for (zv::ArrayEntry entry : innerAccepts.arrRef()) {