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
2 changes: 1 addition & 1 deletion src/Analyser/ExprHandler/AssignHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -1399,7 +1399,7 @@ public function applyWrite(
$nativeType,
TrinaryLogic::createYes(),
[],
)->assignObjectAlias($var->name, $assignedExpr);
)->assignObjectAlias($var->name, $assignedExpr)->assignNarrowedFrom($var->name, $assignedExpr);
foreach ($conditionalExpressions as $exprString => $holders) {
$scope = $scope->addConditionalExpressions((string) $exprString, $holders);
}
Expand Down
6 changes: 4 additions & 2 deletions src/Analyser/ExprHandler/MatchHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -562,11 +562,13 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
// getKeepVoidType() keeps it, so UsageOfVoidMatchExpressionRule
// still sees a void arm
$types = [];
foreach ($armTypeResults as [$armResult]) {
$narrowedFromTypes = [];
foreach ($armTypeResults as [$armResult, $bodyScope, $body]) {
$types[] = $armResult->getKeepVoidType($nativeTypesPromoted);
$narrowedFromTypes[] = ($nativeTypesPromoted ? $bodyScope->doNotTreatPhpDocTypesAsCertain() : $bodyScope)->getNarrowedFromType($body);
}

return TypeCombinator::joinValues(...$types);
return TypeCombinator::joinNarrowedValues($types, $narrowedFromTypes);
},
specifyTypesCallback: fn (TypeSpecifierContext $context, bool $nativeTypesPromoted): SpecifiedTypes => $this->defaultNarrowingHelper->specifyDefaultTypes($expr, $context),
dependencies: Dependencies::merge(...$dependencies),
Expand Down
13 changes: 7 additions & 6 deletions src/Analyser/ExprHandler/TernaryHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
}
$booleanConditionType = ($nativeTypesPromoted ? $ternaryCondResult->getNativeType() : $ternaryCondResult->getType())->toBoolean();
$elseType = $elseResult->getTypeOnScope($elseProcessingScope, $nativeTypesPromoted);
$elseNarrowedFrom = ($nativeTypesPromoted ? $elseProcessingScope->doNotTreatPhpDocTypesAsCertain() : $elseProcessingScope)->getNarrowedFromType($expr->else);
if ($expr->if === null || $ifResult === null) {
// short-ternary truthy value: the condition read on its own truthy
// scope. The truthy narrowing is tracked by the scope
Expand All @@ -194,9 +195,9 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
return $elseType;
}

return TypeCombinator::joinValues(
TypeCombinator::removeFalsey($condTruthyType),
$elseType,
return TypeCombinator::joinNarrowedValues(
[TypeCombinator::removeFalsey($condTruthyType), $elseType],
[$ifProcessingScope->getNarrowedFromType($expr->cond), $elseNarrowedFrom],
);
}

Expand All @@ -209,9 +210,9 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
return $elseType;
}

return TypeCombinator::joinValues(
$ifType,
$elseType,
return TypeCombinator::joinNarrowedValues(
[$ifType, $elseType],
[$ifProcessingScope->getNarrowedFromType($expr->if), $elseNarrowedFrom],
);
},
specifyTypesCallback: function (TypeSpecifierContext $context, bool $nativeTypesPromoted) use ($expr, $ternaryCondResult, $ifResult, $elseResult, $ifProcessingScope, $elseProcessingScope, $nodeScopeResolver, $scope, &$aFalseyScope): SpecifiedTypes {
Expand Down
5 changes: 5 additions & 0 deletions src/Analyser/ExpressionTypeHolder.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,4 +120,9 @@ public function getCertainty(): TrinaryLogic
return $this->certainty;
}

public function getNarrowedFrom(): ?Type
{
return $this->narrowedFrom;
}

}
49 changes: 49 additions & 0 deletions src/Analyser/MutatingScope.php
Original file line number Diff line number Diff line change
Expand Up @@ -1708,6 +1708,22 @@ public function getTrackedExpressionType(Expr $node): Type
return $this->expressionTypes[$this->getNodeKey($node)]->getType();
}

/**
* The type of the value a narrowing refined the tracked expression's type
* from, null when the expression is not tracked or holds a value of its own.
*
* @internal
*/
public function getNarrowedFromType(Expr $node): ?Type
{
$exprString = $this->getNodeKey($node);
if (!array_key_exists($exprString, $this->expressionTypes)) {
return null;
}

return $this->expressionTypes[$exprString]->getNarrowedFrom();
}

/**
* @param MethodReflection|FunctionReflection|null $reflection
*/
Expand Down Expand Up @@ -3884,6 +3900,39 @@ public function assignObjectAlias(string $variableName, Expr $assignedExpr, ?Tri
return $this->specifyObjectAlias($variable, $assignedExpr, $certainty);
}

/**
* The variable just assigned the value of $assignedExpr holds a narrowing of
* the same value $assignedExpr was narrowed from, which a scope merge must
* not keep as a witness type (see ExpressionTypeHolder::and()).
*
* @internal
*/
public function assignNarrowedFrom(string $variableName, Expr $assignedExpr): self
{
$exprString = '$' . $variableName;
$assignedExprString = $this->getNodeKey($assignedExpr);
if ($exprString === $assignedExprString) {
return $this;
}

$holder = $this->expressionTypes[$exprString] ?? null;
$assignedHolder = $this->expressionTypes[$assignedExprString] ?? null;
if ($holder === null || $assignedHolder === null || $assignedHolder->getNarrowedFrom() === null || !$holder->equalTypes($assignedHolder)) {
return $this;
}

$scope = $this->openSpecificationScope();
$scope->expressionTypes[$exprString] = new ExpressionTypeHolder($holder->getExpr(), $holder->getType(), $holder->getCertainty(), $assignedHolder->getNarrowedFrom());

$nativeHolder = $this->nativeExpressionTypes[$exprString] ?? null;
$nativeAssignedHolder = $this->nativeExpressionTypes[$assignedExprString] ?? null;
if ($nativeHolder !== null && $nativeAssignedHolder !== null && $nativeAssignedHolder->getNarrowedFrom() !== null && $nativeHolder->equalTypes($nativeAssignedHolder)) {
$scope->nativeExpressionTypes[$exprString] = new ExpressionTypeHolder($nativeHolder->getExpr(), $nativeHolder->getType(), $nativeHolder->getCertainty(), $nativeAssignedHolder->getNarrowedFrom());
}

return $scope;
}

/**
* Whether the scope knows that both variables hold the same object.
*
Expand Down
29 changes: 29 additions & 0 deletions src/Type/TypeCombinator.php
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,35 @@ public static function joinValues(Type ...$types): Type
return self::witnessAbsorbedTypes($union, ...$types);
}

/**
* joinValues() of values that a narrowing may have refined from another
* value, given at the same key in $narrowedFromTypes. A value narrowed from
* mixed is not one a path produces: it brings to the witness type only the
* part of that mixed's own witness it still allows.
*
* @param list<Type> $types
* @param list<Type|null> $narrowedFromTypes
*/
public static function joinNarrowedValues(array $types, array $narrowedFromTypes): Type
{
$union = self::union(...$types);
if (!$union instanceof MixedType || !self::holdsWitnessType($union) || count($types) < 2) {
return $union;
}

$witnessSources = [];
foreach ($types as $i => $type) {
$narrowedFrom = $narrowedFromTypes[$i] ?? null;
if ($narrowedFrom instanceof MixedType && self::holdsWitnessType($narrowedFrom)) {
$witnessType = $narrowedFrom->getWitnessType();
$type = new MixedType(witnessType: $witnessType !== null ? self::intersect($witnessType, $type) : null);
}
$witnessSources[] = $type;
}

return self::witnessAbsorbedTypes($union, ...$witnessSources);
}

/** A plain mixed or error keeps a witness type; a template or another mixed of its own kind does not. */
private static function holdsWitnessType(Type $type): bool
{
Expand Down
96 changes: 96 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-15943.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
<?php declare(strict_types = 1);

namespace Bug15943;

use function PHPStan\Testing\assertType;

function takesString(string $s): void
{
echo $s;
}

/** @param mixed $v */
function sameValueInTernary($v): void
{
assertType('mixed', is_array($v) ? $v : $v);
takesString(is_array($v) ? $v : $v);
}

/** @param mixed $v */
function sameValueInIfElse($v): void
{
if (is_array($v)) {
$x = $v;
} else {
$x = $v;
}
assertType('mixed', $x);
takesString($x);
}

/** @param mixed $item */
function decode($item): int
{
$decoded = $item ? json_decode($item, true) : $item;
if ($decoded === null) {
return 0;
}

assertType('mixed~(object|null)', $decoded);
return count($decoded);
}

/** @param mixed $v */
function sameValueInMatch($v): void
{
assertType('mixed', match (true) { is_array($v) => $v, default => $v });
takesString(match (true) { is_array($v) => $v, default => $v });
}

/** @param mixed $v */
function sameValueInShortTernary($v): void
{
assertType('mixed', $v ?: $v);
takesString($v ?: $v);
}

/** @param mixed $m */
function producedValues($m, bool $c): void
{
assertType('mixed+1', $c ? $m : 1);
takesString($c ? $m : 1);

assertType('mixed+1', match ($c) { true => $m, false => 1 });
takesString(match ($c) { true => $m, false => 1 });

if (is_array($m)) {
$x = $m;
} else {
$x = 1;
}
assertType('1|array<mixed, mixed>', $x);

if ($c) {
$y = $m;
} else {
$y = 1;
}
assertType('mixed+1', $y);
takesString($y);
}

/** @param mixed $m */
function narrowingKeepsWitness($m, bool $c): void
{
$x = $c ? $m : 1;
assertType('mixed+1', is_int($x) ? $x : $x);
takesString(is_int($x) ? $x : $x);

if (is_int($x)) {
$y = $x;
} else {
$y = $x;
}
assertType('mixed+1', $y);
takesString($y);
}
27 changes: 27 additions & 0 deletions tests/PHPStan/Rules/Functions/CallToFunctionParametersRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3998,6 +3998,33 @@ public function testBug15934(): void
]);
}

public function testBug15943(): void
{
$this->checkMixedWitnessTypes = true;
$this->analyse([__DIR__ . '/../../Analyser/nsrt/bug-15943.php'], [
[
'Parameter #1 $s of function Bug15943\\takesString expects string, int given.',
61,
],
[
'Parameter #1 $s of function Bug15943\\takesString expects string, int given.',
64,
],
[
'Parameter #1 $s of function Bug15943\\takesString expects string, int given.',
79,
],
[
'Parameter #1 $s of function Bug15943\\takesString expects string, int given.',
87,
],
[
'Parameter #1 $s of function Bug15943\\takesString expects string, int given.',
95,
],
]);
}

public function testRecursiveTypes(): void
{
$this->analyse([__DIR__ . '/data/recursive-types.php'], [
Expand Down
1 change: 1 addition & 0 deletions turbo-ext/src/AssignHandler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2154,6 +2154,7 @@ class AssignHandler
AH_VALB(nativeType, readAssignedValueType(nsr, stored, assignedExpr.raw(), nativeScope.raw()));
AH_SETB(scope, pt_mutating_scope_assign_variable(Z_OBJ_P(scope.raw()), varName, type.raw(), nativeType.raw(), ahTrinary(PT_TRI_YES)));
AH_SETB(scope, pt_mutating_scope_assign_object_alias(Z_OBJ_P(scope.raw()), varName, assignedExpr.raw()));
AH_SETB(scope, pt_mutating_scope_assign_narrowed_from(Z_OBJ_P(scope.raw()), varName, assignedExpr.raw()));
for (auto entry : zv::TableRef(Z_ARRVAL_P(conditionalExpressions.raw()))) {
zval *holders = entry.value().raw();
zend_string *exprString = entry.stringKeyOrNull();
Expand Down
6 changes: 6 additions & 0 deletions turbo-ext/src/ExpressionTypeHolder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ class ExpressionTypeHolder
zv::Val getExpr() const { return zv::Val::copyOf(zv::ObjRef(self).propAt(PT_ETH_PROP_EXPR)); }
zv::Val getType() const { return zv::Val::copyOf(zv::ObjRef(self).propAt(PT_ETH_PROP_TYPE)); }
zv::Val getCertainty() const { return zv::Val::copyOf(zv::ObjRef(self).propAt(PT_ETH_PROP_CERTAINTY)); }
zv::Val getNarrowedFrom() const { return zv::Val::copyOf(zv::ObjRef(self).propAt(PT_ETH_PROP_NARROWED_FROM)); }

private:
zval *self;
Expand Down Expand Up @@ -178,6 +179,11 @@ PT_MINIT_REGISTRATION(pt_register_expression_type_holder)
ExpressionTypeHolder(ZEND_THIS).getCertainty().intoReturnValue(return_value);
});

cls.method(sigs::getNarrowedFrom, [](INTERNAL_FUNCTION_PARAMETERS) {
ZEND_PARSE_PARAMETERS_NONE();
ExpressionTypeHolder(ZEND_THIS).getNarrowedFrom().intoReturnValue(return_value);
});

cls.shadow(&pt_ce_expr_type_holder);
}

Expand Down
35 changes: 28 additions & 7 deletions turbo-ext/src/MatchHandler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
*/

#include "support.h"
#include <vector>
#include "generated/MatchHandler.h"
#include "generated/TypeResult.h"

Expand Down Expand Up @@ -1414,17 +1415,37 @@ class MatchHandler
if (UNEXPECTED(!requireArguments(argc, 1, pt_mh_closure_name))) return;
bool nativeTypesPromoted = zend_is_true(&argv[0]);
HashTable *armTypeResults = Z_ARRVAL(captures[0]);
zv::Arr types = zv::Arr::create(zend_hash_num_elements(armTypeResults));
std::vector<zv::Val> types;
std::vector<zv::Val> narrowedFromTypes;
types.reserve(zend_hash_num_elements(armTypeResults));
narrowedFromTypes.reserve(zend_hash_num_elements(armTypeResults));
for (zv::ArrayEntry entry : zv::TableRef(armTypeResults)) {
zval *armResult = zend_hash_index_find(Z_ARRVAL_P(entry.value().raw()), 0);
HashTable *armTypeResult = Z_ARRVAL_P(entry.value().raw());
zval *armResult = zend_hash_index_find(armTypeResult, 0);
zval *bodyScope = zend_hash_index_find(armTypeResult, 1);
zval *body = zend_hash_index_find(armTypeResult, 2);
zv::Val type = pt_expression_result_get_keep_void_type(armResult, nativeTypesPromoted);
if (UNEXPECTED(type.isUndef())) return;
types.push(std::move(type));
types.push_back(std::move(type));
zv::Val promotedBodyScope;
zend_object *narrowingScope = Z_OBJ_P(bodyScope);
if (nativeTypesPromoted) {
promotedBodyScope = pt_mutating_scope_do_not_treat_phpdoc_types_as_certain(narrowingScope);
if (UNEXPECTED(promotedBodyScope.isUndef())) return;
narrowingScope = Z_OBJ_P(promotedBodyScope.raw());
}
zv::Val narrowedFrom = pt_mutating_scope_get_narrowed_from_type(narrowingScope, Z_OBJ_P(body));
if (UNEXPECTED(narrowedFrom.isUndef())) return;
narrowedFromTypes.push_back(std::move(narrowedFrom));
}
/* contiguous borrowed zvals of the owned values */
std::vector<zval> typesArgv(types.size());
std::vector<zval> narrowedFromArgv(types.size());
for (size_t i = 0; i < types.size(); i++) {
ZVAL_COPY_VALUE(&typesArgv[i], types[i].raw());
ZVAL_COPY_VALUE(&narrowedFromArgv[i], narrowedFromTypes[i].raw());
}
HashTable *typesTable = types.table();
zv::Val union_ = HT_IS_PACKED(typesTable) && typesTable->nNumUsed == zend_hash_num_elements(typesTable)
? pt_type_combinator_join_values(zend_hash_num_elements(typesTable), typesTable->arPacked)
: pt_type_combinator_join_values(0, NULL);
zv::Val union_ = pt_type_combinator_join_narrowed_values((uint32_t) types.size(), typesArgv.data(), narrowedFromArgv.data());
if (UNEXPECTED(union_.isUndef())) return;
union_.intoReturnValue(return_value);
}
Expand Down
Loading
Loading