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
25 changes: 22 additions & 3 deletions src/Analyser/MutatingScope.php
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,18 @@ class MutatingScope implements Scope, NodeCallbackInvoker, CollectedDataEmitter,
*/
private static array $globalConstantFetchKeys = [];

/**
* Keys of the merged calls findUninformativeMergedCalls() is resolving.
* Resolving a call processes its arguments again, and merging a ternary
* among them can make the same call a candidate again, e.g. when
* conditional expressions tie the call's type to the ternary's condition
* after `$s = strlen($s ?: '') ?: 0;`. Such a nested check keeps the
* merged entry instead of resolving the call once more.
*
* @var array<string, true>
*/
private static array $resolvingMergedCalls = [];

/**
* @internal accessed by ScopeOps (native and PHP implementations)
* @var array<string, Type>
Expand Down Expand Up @@ -4561,12 +4573,19 @@ private function findUninformativeMergedCalls(array $candidates, array $mergedNa
{
$uninformativeKeys = [];
foreach ($candidates as $exprString => $holder) {
$expr = $holder->getExpr();
if (!$holder->getType()->equals($this->getType($expr))) {
if (isset(self::$resolvingMergedCalls[$exprString])) {
continue;
}
$expr = $holder->getExpr();
$nativeHolder = $mergedNativeTypes[$exprString] ?? null;
if ($nativeHolder !== null && !$nativeHolder->getType()->equals($this->getNativeType($expr))) {
self::$resolvingMergedCalls[$exprString] = true;
try {
$isUninformative = $holder->getType()->equals($this->getType($expr))
&& ($nativeHolder === null || $nativeHolder->getType()->equals($this->getNativeType($expr)));
} finally {
unset(self::$resolvingMergedCalls[$exprString]);
}
if (!$isUninformative) {
continue;
}
$uninformativeKeys[$exprString] = true;
Expand Down
11 changes: 11 additions & 0 deletions tests/PHPStan/Analyser/AnalyserIntegrationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1882,6 +1882,17 @@ public function testBug15520(): void
}
}

#[RequiresPhp('>= 8.0.0')]
public function testBug15754(): void
{
$errors = $this->runAnalyse(__DIR__ . '/data/bug-15754.php');
$this->assertCount(2, $errors);
$this->assertSame('Value assigned to variable $s is never read.', $errors[0]->getMessage());
$this->assertSame(5, $errors[0]->getLine());
$this->assertSame('Parameter #1 $string of function strlen expects string, int<1, max>|string given.', $errors[1]->getMessage());
$this->assertSame(23, $errors[1]->getLine());
}

/**
* @param string[]|null $allAnalysedFiles
* @return list<Error>
Expand Down
26 changes: 26 additions & 0 deletions tests/PHPStan/Analyser/data/bug-15754.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php // lint >= 8.0

namespace Bug15754;

function f(?string $s): void { $s = strlen($s ?: "") ?: 0; }

/**
* @return list<string>
*/
function splitIds(?string $ids): array
{
$ids = preg_split('/,/', $ids ?: '', flags: PREG_SPLIT_NO_EMPTY) ?: [];
foreach ($ids as $id) {
echo $id;
}

return $ids;
}

function twice(?string $s): int
{
$s = strlen($s ?: "") ?: 0;
$s = strlen($s ?: "") ?: 0;

return $s;
}
62 changes: 60 additions & 2 deletions turbo-ext/src/MutatingScope.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8600,26 +8600,81 @@ class MutatingScope
return true;
}

/* MutatingScope::$resolvingMergedCalls - the same static property the twin
* guards findUninformativeMergedCalls() with; NULL = pending exception */
[[nodiscard]] static zval *resolvingMergedCallsTable()
{
if (UNEXPECTED(pt_ce_mutating_scope == NULL)) {
zend_throw_error(NULL, "phpstan_turbo: MutatingScope class entry is not available");
return NULL;
}
zval *table = zend_read_static_property(pt_ce_mutating_scope, PT_LC("resolvingMergedCalls"), 0);
if (UNEXPECTED(table == NULL)) return NULL;
ZVAL_DEREF(table);
if (UNEXPECTED(Z_TYPE_P(table) != IS_ARRAY)) {
zend_throw_error(NULL, "phpstan_turbo: MutatingScope::$resolvingMergedCalls is not an array");
return NULL;
}
return table;
}

/* the twin's `self::$resolvingMergedCalls[$exprString] = true` before
* resolving a candidate and the `unset()` in its `finally`. The static
* property's slot stays put, its array does not - nested checks separate
* and grow it - so it is looked up through the slot on both ends */
class ResolvingMergedCall
{
public:
ResolvingMergedCall(zval *table, zend_string *key, zend_ulong index) : table(table), key(key), index(index)
{
SEPARATE_ARRAY(table);
zval trueZv;
ZVAL_TRUE(&trueZv);
pt_ht_update(Z_ARRVAL_P(table), key, index, &trueZv);
}

~ResolvingMergedCall()
{
if (!pt_ht_exists(Z_ARRVAL_P(table), key, index)) return;
SEPARATE_ARRAY(table);
pt_ht_del(Z_ARRVAL_P(table), key, index);
}

ResolvingMergedCall(const ResolvingMergedCall &) = delete;
ResolvingMergedCall &operator=(const ResolvingMergedCall &) = delete;

private:
zval *table;
zend_string *key;
zend_ulong index;
};

/* private (twin findUninformativeMergedCalls(), called on the merged scope
* without the candidates): keys of candidates whose merged type (and
* native type) is exactly what the call resolves to there */
* native type) is exactly what the call resolves to there. A candidate
* that resolving another candidate (or itself) led back to is kept, like
* the twin's `isset(self::$resolvingMergedCalls[...])` */
static zv::Val findUninformativeMergedCalls(zv::Val &scope, HashTable *candidates, HashTable *mergedNativeTypes)
{
zend_object *scopeObject = requireObject(scope, "getType");
if (UNEXPECTED(scopeObject == NULL)) return zv::Val();
zval *resolving = resolvingMergedCallsTable();
if (UNEXPECTED(resolving == NULL)) return zv::Val();

zv::Arr uninformativeKeys = zv::Arr::create(0);
for (auto entry : zv::TableRef(candidates)) {
zend_string *key = entry.stringKeyOrNull();
if (pt_ht_exists(Z_ARRVAL_P(resolving), key, entry.indexKey())) continue;
zv::Val expr = holderExpr(entry.value());
if (UNEXPECTED(expr.isUndef())) return zv::Val();
zv::Val type = holderType(entry.value());
if (UNEXPECTED(type.isUndef())) return zv::Val();
ResolvingMergedCall resolvingCall(resolving, key, entry.indexKey());
zv::Val freshType = pt_mutating_scope_get_type(scopeObject, expr.raw());
if (UNEXPECTED(freshType.isUndef())) return zv::Val();
bool equal = pt_call_type_equals(type.raw(), freshType.raw());
if (UNEXPECTED(EG(exception) != NULL)) return zv::Val();
if (!equal) continue;
zend_string *key = entry.stringKeyOrNull();
zval *nativeHolder = key != NULL ? zend_hash_find(mergedNativeTypes, key) : zend_hash_index_find(mergedNativeTypes, entry.indexKey());
if (nativeHolder != NULL) {
zv::Val nativeType = holderType(zv::Ref(nativeHolder));
Expand Down Expand Up @@ -12542,6 +12597,9 @@ PT_MINIT_REGISTRATION(pt_register_mutating_scope)
* static takes no OBJ_PROP_NUM slot, and keeping it out of the run above
* keeps that run a literal transcript of the PT_MS_PROP_* enum */
cls.privateStaticTypedArrayPropertyDefaultEmpty("globalConstantFetchKeys");
/* the twin's `private static array $resolvingMergedCalls = []`, the
* re-entry guard of findUninformativeMergedCalls() on both sides */
cls.privateStaticTypedArrayPropertyDefaultEmpty("resolvingMergedCalls");
cls.privateClassConstantLong("COMPLEX_UNION_TYPE_MEMBER_LIMIT", PT_MS_COMPLEX_UNION_TYPE_MEMBER_LIMIT);
cls.privateClassConstantLong("GLOBAL_CONSTANT_FETCH_KEYS_LIMIT", PT_MS_GLOBAL_CONSTANT_FETCH_KEYS_LIMIT);
pt_ms_custom_serialization_methods_list = pt_persistent_string_list(pt_ms_custom_serialization_methods, sizeof(pt_ms_custom_serialization_methods) / sizeof(pt_ms_custom_serialization_methods[0]));
Expand Down
1 change: 1 addition & 0 deletions turbo-ext/src/generated/MutatingScope.h
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ inline void declareClass(reg::Class &cls)
inline void declareProperties(reg::Class &cls)
{
cls.property("globalConstantFetchKeys", ZEND_ACC_PRIVATE | ZEND_ACC_STATIC, reg::PropertyKind::TypedEmptyArray, MAY_BE_ARRAY);
cls.property("resolvingMergedCalls", ZEND_ACC_PRIVATE | ZEND_ACC_STATIC, reg::PropertyKind::TypedEmptyArray, MAY_BE_ARRAY);
cls.property("resolvedTypes", ZEND_ACC_PUBLIC, reg::PropertyKind::TypedEmptyArray, MAY_BE_ARRAY);
cls.property("nodeCallbackScope", ZEND_ACC_PRIVATE, reg::PropertyKind::TypedNull, MAY_BE_NULL, "PHPStan\\Analyser\\MutatingScope");
cls.property("namespace", ZEND_ACC_PRIVATE, reg::PropertyKind::Typed, MAY_BE_NULL | MAY_BE_STRING);
Expand Down
Loading