Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions src/Command/ErrorFormatter/ConsoleTagEscaper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php declare(strict_types = 1);

namespace PHPStan\Command\ErrorFormatter;

use Symfony\Component\Console\Formatter\OutputFormatter;
use function preg_match;
use function preg_replace_callback;

/**
* Escapes the `<...>` in an error message or tip that are not console style tags,
* such as `array<int, string>` in a type description, keeping `<fg=cyan>...</>`
* 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,
);
}

}
2 changes: 1 addition & 1 deletion src/Command/ErrorFormatter/JsonErrorFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
6 changes: 3 additions & 3 deletions src/Command/ErrorFormatter/TableErrorFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 = '<fg=red>' . OutputFormatter::escape($message) . '</>';
$message = '<fg=red>' . OutputFormatter::escape($error->getMessage()) . '</>';
}
if ($error->getFixedErrorDiffs() !== []) {
$message .= ' 🔧';
Expand All @@ -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")) {
Expand Down
16 changes: 15 additions & 1 deletion src/Type/AcceptsResult.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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;
Expand All @@ -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<string> */
public readonly array $reasons;

/**
* @phpstan-assert-if-true =false $this->no()
* @phpstan-assert-if-true =false $this->maybe()
Expand Down
61 changes: 61 additions & 0 deletions src/Type/ArrayAlgebra.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<ConstantArrayType>|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
{
Expand Down
19 changes: 19 additions & 0 deletions src/Type/UnionType.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,7 @@ public static function dataFormatTip(): iterable
yield ['tip', 'tip'];
yield ['<fg=cyan>%configurationFile%</>', '%configurationFile%'];
yield ['this check by setting <fg=cyan>treatPhpDocTypesAsCertain: false</> in your <fg=cyan>%configurationFile%</>.', 'this check by setting treatPhpDocTypesAsCertain: false in your %configurationFile%.'];
yield ["Offset 'a' (array<string, array<int, string>>) does not accept type <fg=cyan>list<\\Foo></>.", "Offset 'a' (array<string, array<int, string>>) does not accept type list<\\Foo>."];
}

#[DataProvider('dataFormatTip')]
Expand Down
11 changes: 11 additions & 0 deletions tests/PHPStan/Rules/Methods/ReturnTypeRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, array<string, string>>} 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'.",
],
]);
}

}
46 changes: 46 additions & 0 deletions tests/PHPStan/Rules/Methods/data/accepts-merged-shapes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php declare(strict_types = 1);

namespace AcceptsMergedShapes;

/**
* @phpstan-type PBool array{type: 'boolean', name: string}
* @phpstan-type PKeyword array{type: 'keyword', name: string, fields?: array<string, array<string, string>>}
* @phpstan-type P PBool|PKeyword|array{type: 'date', name: string, format: string}
* @phpstan-type PObject array{type: 'object', properties: array<non-empty-string, P>}
*/
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];
}

}
26 changes: 26 additions & 0 deletions turbo-ext/src/AcceptsResult.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -438,6 +461,7 @@ class AcceptsResult
ZVAL_COPY(&copy, result);
pt_readonly_slot_init(self, PT_RESULT_PROP_RESULT, &copy);
ZVAL_COPY(&copy, reasons);
pt_accepts_result_cap_reasons(&copy);
pt_readonly_slot_init(self, PT_RESULT_PROP_REASONS, &copy);
return true;
}
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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;
Expand Down
32 changes: 32 additions & 0 deletions turbo-ext/src/UnionType.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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()) {
Expand Down
Loading