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
71 changes: 67 additions & 4 deletions src/Analyser/ExprHandler/AssignHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@
use function array_reverse;
use function array_slice;
use function count;
use function get_class;
use function in_array;
use function is_float;
use function is_int;
Expand Down Expand Up @@ -2396,6 +2397,19 @@ private function processDerivedConditionalExpressionsAfterAssign(
$seenReadExprStrings = [];
/** @var Variable[] $readVariables */
$readVariables = (new NodeFinder())->findInstanceOf([$assignedExpr], Variable::class);
// arithmetic over variables reads nothing but their types: a condition on another
// variable cannot change what it evaluates to and is not assigned, and with no
// condition left the result depends on the consequent alone
$readVariableNames = null;
if (self::readsOnlyItsVariables($pricedExpr)) {
$readVariableNames = [];
foreach ($readVariables as $readVariable) {
if (!is_string($readVariable->name)) {
continue;
}
$readVariableNames['$' . $readVariable->name] = true;
}
}
foreach ($readVariables as $readVariable) {
if (!is_string($readVariable->name) || $readVariable->name === $variableName) {
continue;
Expand All @@ -2406,28 +2420,50 @@ private function processDerivedConditionalExpressionsAfterAssign(
}
$seenReadExprStrings[$readExprString] = true;

$derivedTypesByConsequent = [];
foreach ($scopeConditionalExpressions[$readExprString] ?? [] as $holder) {
$consequent = $holder->getTypeHolder();
if (!$consequent->getCertainty()->yes()) {
continue;
}

$conditionHolders = $holder->getConditionExpressionTypeHolders();
$evalScope = $scope;
$assignedConditionHolders = [];
foreach ($conditionHolders as $conditionExprString => $conditionHolder) {
if ($conditionExprString === $targetExprString || !$conditionHolder->getCertainty()->yes()) {
// a condition on the just-overwritten variable is stale
continue 2;
}
$evalScope = $evalScope->assignExpression($conditionHolder->getExpr(), $conditionHolder->getType(), $conditionHolder->getType());
if ($readVariableNames !== null && $conditionHolder->getExpr() instanceof Variable && !isset($readVariableNames[$conditionExprString])) {
continue;
}
$assignedConditionHolders[] = $conditionHolder;
}

if (++$evaluations > self::DERIVED_CONDITIONAL_EXPRESSIONS_LIMIT) {
return $conditionalExpressions;
}

$evalScope = $evalScope->assignExpression($consequent->getExpr(), $consequent->getType(), $consequent->getType());
$derivedType = $nodeScopeResolver->readScopeStateOrSyntheticType($pricedExpr, $evalScope);
$derivedType = null;
if ($readVariableNames !== null && count($assignedConditionHolders) === 0) {
foreach ($derivedTypesByConsequent as [$consequentType, $consequentDerivedType]) {
if ($consequentType->equals($consequent->getType())) {
$derivedType = $consequentDerivedType;
break;
}
}
}
if ($derivedType === null) {
$evalScope = $scope;
foreach ($assignedConditionHolders as $conditionHolder) {
$evalScope = $evalScope->assignExpression($conditionHolder->getExpr(), $conditionHolder->getType(), $conditionHolder->getType());
}
$evalScope = $evalScope->assignExpression($consequent->getExpr(), $consequent->getType(), $consequent->getType());
$derivedType = $nodeScopeResolver->readScopeStateOrSyntheticType($pricedExpr, $evalScope);
if ($readVariableNames !== null && count($assignedConditionHolders) === 0) {
$derivedTypesByConsequent[] = [$consequent->getType(), $derivedType];
}
}
if ($derivedType->equals($assignedType)) {
continue;
}
Expand All @@ -2443,6 +2479,33 @@ private function processDerivedConditionalExpressionsAfterAssign(
return $conditionalExpressions;
}

/**
* Whether the type of $expr is read from the types of the variables it mentions alone:
* arithmetic, concatenation and bitwise operators over named variables, literals and
* constants - nothing in it is read in a narrowed scope or calls anything that could
* look up another variable.
*/
private static function readsOnlyItsVariables(Expr $expr): bool
{
if ($expr instanceof Variable) {
return is_string($expr->name);
}
if ($expr instanceof Node\Scalar) {
return !$expr instanceof Node\Scalar\InterpolatedString;
}
if ($expr instanceof Expr\ConstFetch) {
return true;
}
if ($expr instanceof Expr\UnaryMinus || $expr instanceof Expr\UnaryPlus || $expr instanceof Expr\Cast) {
return self::readsOnlyItsVariables($expr->expr);
}
if ($expr instanceof Expr\BinaryOp && !$expr instanceof Expr\BinaryOp\Coalesce && in_array(get_class($expr), self::ASSIGN_OP_BINARY_OPS, true)) {
return self::readsOnlyItsVariables($expr->left) && self::readsOnlyItsVariables($expr->right);
}

return false;
}

/**
* Records the reverse implication of a `$var = in_array($needle, [...known values])`
* assignment: a needle that is one of the haystack's always-present values makes the
Expand Down
19 changes: 17 additions & 2 deletions src/Analyser/ExprHandler/NullsafeMethodCallHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use function array_merge;
use function get_class;

/**
* @implements ExprHandler<NullsafeMethodCall>
Expand Down Expand Up @@ -136,6 +137,10 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
$receiverResult = $processedReceiverResult;
// lazily memoized receiver-is-null branch scope of the decomposition
$leftFalseyScope = null;
// "this link did not short-circuit", by $nativeTypesPromoted: the link after this one
// asks for it twice, through its plain twin's receiver and through its own receiver
// term, so without it a chain N links deep would narrow its first link 2^N times
$notNullTypes = [];

return $this->expressionResultFactory->create(
$scope,
Expand Down Expand Up @@ -193,13 +198,18 @@ static function () use ($beforeScope, $leftTypes, &$leftFalseyScope): MutatingSc
// Inside-out copy of TypeSpecifier::createForExpr()'s `?->` handling.
// The short-circuit's null surfaces here, never by walking the chain:
// a receiver that is itself a ?-> composes through the parent handler.
createTypesCallback: function (Type $type, TypeSpecifierContext $context, bool $nativeTypesPromoted) use ($expr, $methodCall, $exprResult, $receiverResult, $nullsafeTypeCallback, $beforeScope): SpecifiedTypes {
createTypesCallback: function (Type $type, TypeSpecifierContext $context, bool $nativeTypesPromoted) use ($expr, $methodCall, $exprResult, $receiverResult, $nullsafeTypeCallback, $beforeScope, &$notNullTypes): SpecifiedTypes {
// null() context: createForExpr never computes $containsNull and
// emits no entry for the subject - behave the same.
if ($context->null()) {
return (new SpecifiedTypes())->setRootExpr($expr);
}

$isNotNull = get_class($type) === NullType::class && $context === TypeSpecifierContext::createFalse();
if ($isNotNull && isset($notNullTypes[(int) $nativeTypesPromoted])) {
return $notNullTypes[(int) $nativeTypesPromoted];
}

$s = $nativeTypesPromoted ? $beforeScope->doNotTreatPhpDocTypesAsCertain() : $beforeScope;
$nullsafeType = $nullsafeTypeCallback($nativeTypesPromoted);
if ($context->true()) {
Expand All @@ -220,10 +230,15 @@ static function () use ($beforeScope, $leftTypes, &$leftFalseyScope): MutatingSc
// double-key), and "receiver is not null".
// the receiver composes through its own result so a nullsafe
// receiver fans "not null" down its whole chain
return $this->defaultNarrowingHelper->createSubjectTypes($s, $methodCall, $exprResult, $type, $context)
$types = $this->defaultNarrowingHelper->createSubjectTypes($s, $methodCall, $exprResult, $type, $context)
->unionWith($this->defaultNarrowingHelper->createSubjectTypes($s, $expr, null, $type, $context))
->unionWith($this->defaultNarrowingHelper->createSubjectTypes($s, $expr->var, $receiverResult, new NullType(), TypeSpecifierContext::createFalse()))
->setRootExpr($expr);
if ($isNotNull) {
$notNullTypes[(int) $nativeTypesPromoted] = $types;
}

return $types;
},
dependencies: Dependencies::merge($exprResult->getDependencies(), $processedReceiverResult->getDependencies()),
);
Expand Down
19 changes: 17 additions & 2 deletions src/Analyser/ExprHandler/NullsafePropertyFetchHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use function array_merge;
use function get_class;

/**
* @implements ExprHandler<NullsafePropertyFetch>
Expand Down Expand Up @@ -114,6 +115,10 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
$receiverResult = $processedReceiverResult;
// lazily memoized receiver-is-null branch scope of the decomposition
$leftFalseyScope = null;
// "this link did not short-circuit", by $nativeTypesPromoted: the link after this one
// asks for it twice, through its plain twin's receiver and through its own receiver
// term, so without it a chain N links deep would narrow its first link 2^N times
$notNullTypes = [];

return $this->expressionResultFactory->create(
$scope,
Expand Down Expand Up @@ -171,13 +176,18 @@ static function () use ($beforeScope, $leftTypes, &$leftFalseyScope): MutatingSc
// Inside-out copy of TypeSpecifier::createForExpr()'s `?->` handling.
// The short-circuit's null surfaces here, never by walking the chain:
// a receiver that is itself a ?-> composes through the parent handler.
createTypesCallback: function (Type $type, TypeSpecifierContext $context, bool $nativeTypesPromoted) use ($expr, $propertyFetch, $exprResult, $receiverResult, $nullsafeTypeCallback, $beforeScope): SpecifiedTypes {
createTypesCallback: function (Type $type, TypeSpecifierContext $context, bool $nativeTypesPromoted) use ($expr, $propertyFetch, $exprResult, $receiverResult, $nullsafeTypeCallback, $beforeScope, &$notNullTypes): SpecifiedTypes {
// null() context: createForExpr never computes $containsNull and
// emits no entry for the subject - behave the same.
if ($context->null()) {
return (new SpecifiedTypes())->setRootExpr($expr);
}

$isNotNull = get_class($type) === NullType::class && $context === TypeSpecifierContext::createFalse();
if ($isNotNull && isset($notNullTypes[(int) $nativeTypesPromoted])) {
return $notNullTypes[(int) $nativeTypesPromoted];
}

$s = $nativeTypesPromoted ? $beforeScope->doNotTreatPhpDocTypesAsCertain() : $beforeScope;
$nullsafeType = $nullsafeTypeCallback($nativeTypesPromoted);
if ($context->true()) {
Expand All @@ -198,10 +208,15 @@ static function () use ($beforeScope, $leftTypes, &$leftFalseyScope): MutatingSc
// double-key), and "receiver is not null".
// the receiver composes through its own result so a nullsafe
// receiver fans "not null" down its whole chain
return $this->defaultNarrowingHelper->createSubjectTypes($s, $propertyFetch, $exprResult, $type, $context)
$types = $this->defaultNarrowingHelper->createSubjectTypes($s, $propertyFetch, $exprResult, $type, $context)
->unionWith($this->defaultNarrowingHelper->createSubjectTypes($s, $expr, null, $type, $context))
->unionWith($this->defaultNarrowingHelper->createSubjectTypes($s, $expr->var, $receiverResult, new NullType(), TypeSpecifierContext::createFalse()))
->setRootExpr($expr);
if ($isNotNull) {
$notNullTypes[(int) $nativeTypesPromoted] = $types;
}

return $types;
},
dependencies: Dependencies::merge($exprResult->getDependencies(), $processedReceiverResult->getDependencies()),
);
Expand Down
16 changes: 16 additions & 0 deletions src/Analyser/VariableFlow.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use PHPStan\Node\Variable\VariableWrite;
use PHPStan\Turbo\ShadowedByTurboExtension;
use PHPStan\Type\Type;
use function array_slice;
use function count;
use function in_array;

Expand Down Expand Up @@ -74,6 +75,21 @@ public static function choice(?self ...$branches): ?self
if (count($branches) === 1 || (count($branches) === 2 && $branches[0] === $branches[1])) {
return $branches[0];
}
if (count($branches) === 2) {
// Both branches start with the same flow, like a `?->` and its short circuit that
// both evaluate the receiver: it runs once before the choice of the rest, or the
// receiver of a chain N links deep would be walked 2^N times.
foreach ([[$branches[0], $branches[1]], [$branches[1], $branches[0]]] as [$longer, $prefix]) {
if (
$prefix !== null
&& $longer instanceof VariableSequenceFlow
&& $longer->kind === self::SEQUENCE
&& $longer->children[0] === $prefix
) {
return self::sequence($prefix, new VariableSequenceFlow(self::CHOICE, [self::sequence(...array_slice($longer->children, 1)), null]));
}
}
}

return new VariableSequenceFlow(self::CHOICE, $branches);
}
Expand Down
64 changes: 64 additions & 0 deletions src/Analyser/VariableLivenessResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,9 @@ final class VariableLivenessResolver

private bool $returnsByReference = false;

/** @var array<int, array{array<string, true>, VariableFlowContext, array<string, true>}> loop flow id => the live sets after it and the head they resolved to */
private array $loopHeads = [];

private function __construct()
{
}
Expand Down Expand Up @@ -342,7 +345,18 @@ private function liveBefore(?VariableFlow $flow, array $next, VariableFlowContex
return $next + $names;
}
if ($flow->kind === VariableFlow::LOOP) {
// Liveness only grows with the live sets after the loop, so the head the loop
// resolved to for smaller sets is below the new one and the iteration can start
// from it. Each pass of an enclosing loop asks again with sets at least as large,
// so a loop nested N deep is no longer walked 2^N times.
$head = [];
$flowId = spl_object_id($flow);
if (isset($this->loopHeads[$flowId])) {
[$previousNext, $previousContext, $previousHead] = $this->loopHeads[$flowId];
if (self::covers($next, $previousNext) && self::contextCovers($context, $previousContext)) {
$head = $previousHead;
}
}
do {
$previousCount = count($head);
$update = $this->liveBefore($flow->children[2], $head, $context);
Expand All @@ -351,6 +365,7 @@ private function liveBefore(?VariableFlow $flow, array $next, VariableFlowContex
$afterCondition = $flow->canRepeat ? ($flow->canExit ? $body + $next : $body) : $next;
$head = $this->liveBefore($flow->children[0], $afterCondition, $context);
} while (count($head) !== $previousCount);
$this->loopHeads[$flowId] = [$next, $context, $head];

return $flow->atLeastOnce ? $this->liveBefore($flow->children[0], $body, $context) : $head;
}
Expand Down Expand Up @@ -721,6 +736,55 @@ private function killOverwriteMarkers(VariableWrite $write, array $next): array
return self::withoutKeys($next, $markersBySlot[$slot] ?? []);
}

/**
* @param array<string, true> $set
* @param array<string, true> $subset
*/
private static function covers(array $set, array $subset): bool
{
if (count($set) < count($subset)) {
return false;
}
foreach (array_keys($subset) as $key) {
if (!isset($set[$key])) {
return false;
}
}

return true;
}

/** Whether each destination of $context covers the same one of $subcontext. */
private static function contextCovers(VariableFlowContext $context, VariableFlowContext $subcontext): bool
{
if (
count($context->breaks) !== count($subcontext->breaks)
|| count($context->continues) !== count($subcontext->continues)
|| count($context->catches) !== count($subcontext->catches)
|| !self::covers($context->return, $subcontext->return)
|| !self::covers($context->uncaught, $subcontext->uncaught)
) {
return false;
}
foreach ($subcontext->breaks as $i => $destination) {
if (!self::covers($context->breaks[$i], $destination)) {
return false;
}
}
foreach ($subcontext->continues as $i => $destination) {
if (!self::covers($context->continues[$i], $destination)) {
return false;
}
}
foreach ($subcontext->catches as $i => [$type, $destination]) {
if ($context->catches[$i][0] !== $type || !self::covers($context->catches[$i][1], $destination)) {
return false;
}
}

return true;
}

/**
* Walks the smaller of the two sets.
*
Expand Down
8 changes: 5 additions & 3 deletions src/Reflection/ClassReflection.php
Original file line number Diff line number Diff line change
Expand Up @@ -277,16 +277,18 @@ public function getParentClass(): ?ClassReflection
);
}

// a generic parent is a new reflection, remembered so that walking up a generic
// hierarchy does not resolve each ancestor again from every class below it
if (!$extendedType instanceof GenericObjectType) {
return $this->reflectionProvider->getClass($parentClass->getName());
return $this->cachedParentClass = $this->reflectionProvider->getClass($parentClass->getName());
}

return $extendedType->getClassReflection() ?? $this->reflectionProvider->getClass($parentClass->getName());
return $this->cachedParentClass = $extendedType->getClassReflection() ?? $this->reflectionProvider->getClass($parentClass->getName());
}

$parentReflection = $this->reflectionProvider->getClass($parentClass->getName());
if ($parentReflection->isGeneric()) {
return $parentReflection->withTypes(
return $this->cachedParentClass = $parentReflection->withTypes(
array_values($parentReflection->getTemplateTypeMap()->map(static fn (): Type => new ErrorType())->getTypes()),
);
}
Expand Down
13 changes: 12 additions & 1 deletion src/Rules/Generics/CrossCheckInterfacesHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,18 @@ public function check(ClassReflection $classReflection): array
{
$interfaceTemplateTypeMaps = [];
$errors = [];
$check = static function (ClassReflection $classReflection, bool $first) use (&$interfaceTemplateTypeMaps, &$check, &$errors): void {
// Each ancestor is reached once from every class below it, and a class seen again
// compares the same interfaces with the same maps, repeating only its errors - visiting
// it every time was exponential in the depth of the hierarchy.
$visited = [];
$check = static function (ClassReflection $classReflection, bool $first) use (&$interfaceTemplateTypeMaps, &$check, &$errors, &$visited): void {
if (!$first) {
if (array_key_exists($classReflection->getName(), $visited)) {
return;
}
$visited[$classReflection->getName()] = true;
}

foreach ($classReflection->getInterfaces() as $interface) {
if (!$interface->isGeneric()) {
continue;
Expand Down
Loading
Loading