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
14 changes: 9 additions & 5 deletions src/Analyser/ArgumentsHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ public function processArgs(
}
$gatheredArgTypeByIndex[$i] = $solvedClosureTypes[$i] ?? $this->gatherClosureArgType($parametersAcceptors, $i, $arg->value, $scope, $gatheredTypes);
} else {
$gatheredArgTypeByIndex[$i] = $this->closureTypeResolver->getClosureType($scope, $arg->value, true, $storage);
$gatheredArgTypeByIndex[$i] = $this->closureTypeResolver->getShallowClosureType($scope, $arg->value, $storage);
}
$this->addGatheredArgType($gatheredTypes, $gatheredUnpack, $gatheredHasName, $originalArgForGather, $i, $gatheredArgTypeByIndex[$i]);
}
Expand Down Expand Up @@ -362,6 +362,10 @@ public function processArgs(
$scopeToPass = $closureBindScopeFactory($scope);
}

if ($arg->value instanceof Expr\Closure || $arg->value instanceof Expr\ArrowFunction) {
ClosureProcessor::markCallbackArgument($arg->value, $this->callCallbackImmediately($parameter, $parameterType, $calleeReflection));
}

if ($arg->value instanceof Expr\Closure) {

$storedClosureArgResult = null;
Expand All @@ -381,8 +385,8 @@ public function processArgs(
isAlwaysTerminating: false,
throwPoints: [],
impurePoints: [],
type: $this->closureTypeResolver->getClosureType($scopeToPass, $arg->value, false, $storage),
nativeType: $this->closureTypeResolver->getClosureType($scopeToPass->doNotTreatPhpDocTypesAsCertain(), $arg->value, false, $storage),
type: $this->closureProcessor->getClosureType($scopeToPass, $arg->value, $storage),
nativeType: $this->closureProcessor->getClosureType($scopeToPass->doNotTreatPhpDocTypesAsCertain(), $arg->value, $storage),
typeCallback: null,
specifyTypesCallback: SpecifiedTypes::emptySpecifyCallback(),
);
Expand Down Expand Up @@ -531,8 +535,8 @@ public function processArgs(
isAlwaysTerminating: false,
throwPoints: [],
impurePoints: [],
type: $this->closureTypeResolver->getClosureType($scopeToPass, $arg->value, false, $storage),
nativeType: $this->closureTypeResolver->getClosureType($scopeToPass->doNotTreatPhpDocTypesAsCertain(), $arg->value, false, $storage),
type: $this->closureProcessor->getClosureType($scopeToPass, $arg->value, $storage),
nativeType: $this->closureProcessor->getClosureType($scopeToPass->doNotTreatPhpDocTypesAsCertain(), $arg->value, $storage),
typeCallback: null,
specifyTypesCallback: SpecifiedTypes::emptySpecifyCallback(),
);
Expand Down
225 changes: 217 additions & 8 deletions src/Analyser/ClosureProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@
use PHPStan\Analyser\ExprHandler\ArrowFunctionHandler;
use PHPStan\Analyser\ExprHandler\Helper\ClosureParameterResolver;
use PHPStan\Analyser\ExprHandler\Helper\ClosureTypeResolver;
use PHPStan\Analyser\ExprHandler\Helper\ClosureWalkTemplateTypes;
use PHPStan\Analyser\ExprHandler\Helper\ContextualClosureParameterResolver;
use PHPStan\Analyser\Generics\ClosureSignatureInference;
use PHPStan\Analyser\Generics\TemplateArgumentStats;
use PHPStan\Dependency\Dependencies;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\DependencyInjection\Container;
Expand Down Expand Up @@ -42,6 +44,7 @@
use function count;
use function in_array;
use function is_string;
use function spl_object_id;

/**
* Walks closure and arrow function bodies for NodeScopeResolver and builds
Expand Down Expand Up @@ -103,6 +106,212 @@ private function processAttributeGroupsAndParams(
);
}

/**
* Set by ArgumentsHandler on a closure or arrow function written as a call
* argument: whether the parameter calls it during the call - decided like
* ArgumentsHandler::callCallbackImmediately(), so an untagged method
* parameter needs @param-immediately-invoked-callable.
*/
private const INVOKED_DURING_CALL_ATTRIBUTE = 'phpstanInvokedDuringCall';

public static function markCallbackArgument(Expr\Closure|Expr\ArrowFunction $expr, bool $invokedDuringCall): void
{
$expr->setAttribute(self::INVOKED_DURING_CALL_ATTRIBUTE, $invokedDuringCall);
}

/**
* The function's scope as it runs. It sees the objects it captures by
* handle, so a property narrowed where it is created can be reassigned
* before it runs - unless it runs right where it is written: invoked
* immediately, or passed to a parameter that calls it during the call.
* Every walk of the body enters through here.
*/
private static function enterWhereInvoked(MutatingScope $functionScope, Expr\Closure|Expr\ArrowFunction $expr): MutatingScope
{
if (
$expr->getAttribute(ImmediatelyInvokedClosureVisitor::ATTRIBUTE_NAME) === true
|| $expr->getAttribute(self::INVOKED_DURING_CALL_ATTRIBUTE) === true
) {
return $functionScope;
}

return $functionScope->forgetMutablePropertyFetches();
}

/**
* Guards the walks of getClosureType(): a closure whose body asks for its
* own type (use (&$self)) is answered with its signature from the second
* nested walk on.
*/
private static int $closureTypeWalkDepth = 0;

/**
* Counts the closure types the depth guard answered without a walk. A
* walk that sees it change stored the types of nested closures it could
* not walk, so its return types are priced again on the scope once the
* guard is lower.
*/
private static int $cappedClosureTypeWalks = 0;

/**
* The type of a closure or arrow function whose expression result is not
* stored: asked before its own walk stored it (its body asks for it, a
* callable parameter is derived from it while it is processed), priced
* for a call argument walked on demand, or typed for other parameter or
* by-ref use types than the ones it is written with. The body is walked
* here, without reporting anything - this is the only body walk besides
* processClosureNode()/processArrowFunctionNode(), so a closure is always
* entered the same way.
*
* $passedToType types the parameters like a callable parameter the closure
* is passed to does - FuncCallHandler passes the arguments of an invocation.
* $byRefUseTypes types variables the closure uses by reference, which the
* walk otherwise enters as mixed - resolveAssignedClosureType().
*
* @param array<string, Type> $byRefUseTypes
*/
public function getClosureType(
MutatingScope $scope,
Expr\Closure|Expr\ArrowFunction $expr,
?ExpressionResultStorage $storage = null,
?Type $passedToType = null,
array $byRefUseTypes = [],
): ClosureType
{
$templateSuffix = '@' . spl_object_id($expr);
[$passedToType, $nativePassedToType] = $this->closureTypeResolver->getWalkPassedToTypes($scope, $passedToType, $templateSuffix);
$cached = $this->closureTypeResolver->findCachedClosureType($scope, $expr, $storage, $passedToType, $nativePassedToType, $byRefUseTypes, $templateSuffix);
if ($cached !== null) {
return $cached;
}
if (self::$closureTypeWalkDepth >= 2) {
self::$cappedClosureTypeWalks++;
return $this->closureTypeResolver->getShallowClosureType($scope, $expr, $storage, $passedToType);
}
if (TemplateArgumentStats::$enabled) {
TemplateArgumentStats::increment('closureTypeBodyWalks');
}

$nodeScopeResolver = $this->container->getByType(NodeScopeResolver::class);
$parameterTypes = $this->contextualClosureParameterResolver->resolve($scope, $expr, $storage, $passedToType, $nativePassedToType);
$invalidateExpressions = [];
$impurePoints = [];
self::$closureTypeWalkDepth++;
$cappedBefore = self::$cappedClosureTypeWalks;
$walkStorage = new ExpressionResultStorage();
if ($expr instanceof Expr\ArrowFunction) {
$arrowScope = self::enterWhereInvoked($scope->enterArrowFunctionWithoutReflection($expr, $parameterTypes->parameters, $parameterTypes->nativeParameters), $expr);
$arrowScope->pushExpressionResultStorage($walkStorage);
try {
$exprResult = $nodeScopeResolver->processExprNode(
new Node\Stmt\Expression($expr->expr),
$expr->expr,
$arrowScope,
$walkStorage,
self::createClosureTypeGatherer($arrowScope, $impurePoints, $invalidateExpressions),
ExpressionContext::createDeep(),
);
} finally {
$arrowScope->popExpressionResultStorage();
self::$closureTypeWalkDepth--;
}

return ClosureWalkTemplateTypes::restore($this->closureTypeResolver->buildClosureTypeForArrowFunction(
$scope,
$expr,
$arrowScope,
array_map(static fn (InternalThrowPoint $throwPoint) => $throwPoint->toPublic(), $exprResult->getThrowPoints()),
array_merge($impurePoints, $exprResult->getImpurePoints()),
$invalidateExpressions,
false,
self::$cappedClosureTypeWalks === $cappedBefore ? $walkStorage : null,
$passedToType,
$nativePassedToType,
$byRefUseTypes,
), $templateSuffix);
}

$closureScope = self::enterWhereInvoked($scope->enterAnonymousFunctionWithoutReflection($expr, $parameterTypes->parameters, $parameterTypes->nativeParameters), $expr);
foreach ($byRefUseTypes as $name => $byRefUseType) {
$closureScope = $closureScope->assignVariable($name, $byRefUseType, $byRefUseType, TrinaryLogic::createYes());
}
$returnStatements = [];
$yieldStatements = [];
$executionEnds = [];
$closureScope->pushExpressionResultStorage($walkStorage);
try {
$statementResult = $nodeScopeResolver->processStmtNodesInternal(
$expr,
$expr->stmts,
$closureScope,
$walkStorage,
self::createClosureTypeGatherer($closureScope, $impurePoints, $invalidateExpressions, $returnStatements, $yieldStatements, $executionEnds),
StatementContext::createTopLevel(),
);
} finally {
$closureScope->popExpressionResultStorage();
self::$closureTypeWalkDepth--;
}

return ClosureWalkTemplateTypes::restore($this->closureTypeResolver->buildClosureTypeForClosure(
$scope,
$expr,
$returnStatements,
$yieldStatements,
$executionEnds,
$statementResult->getThrowPoints(),
array_merge($impurePoints, $statementResult->getImpurePoints()),
$invalidateExpressions,
false,
self::$cappedClosureTypeWalks === $cappedBefore ? $walkStorage : null,
$passedToType,
$nativePassedToType,
$byRefUseTypes,
), $templateSuffix);
}

/**
* The node callback of a getClosureType() walk: gathers what the closure
* type is built from, for nodes of the walked function only.
*
* @param ImpurePoint[] $impurePoints
* @param InvalidateExprNode[] $invalidateExpressions
* @param list<array{Return_, Scope}> $returnStatements
* @param list<array{Expr\Yield_|Expr\YieldFrom, Scope}> $yieldStatements
* @param list<ExecutionEndNode> $executionEnds
* @return callable(Node, Scope): void
*/
private static function createClosureTypeGatherer(MutatingScope $functionScope, array &$impurePoints, array &$invalidateExpressions, array &$returnStatements = [], array &$yieldStatements = [], array &$executionEnds = []): callable
{
return static function (Node $node, Scope $scope) use ($functionScope, &$impurePoints, &$invalidateExpressions, &$returnStatements, &$yieldStatements, &$executionEnds): void {
if ($scope->getAnonymousFunctionReflection() !== $functionScope->getAnonymousFunctionReflection()) {
return;
}
if ($node instanceof InvalidateExprNode) {
$invalidateExpressions[] = $node;
return;
}
if ($node instanceof PropertyAssignNode) {
$impurePoints[] = new ImpurePoint($scope, $node, 'propertyAssign', 'property assignment', true);
$invalidateExpressions[] = new InvalidateExprNode($node->getPropertyFetch());
return;
}
if ($node instanceof ExecutionEndNode) {
$executionEnds[] = $node;
return;
}
if ($node instanceof Return_) {
$returnStatements[] = [$node, $scope];
return;
}
if (!$node instanceof Expr\Yield_ && !$node instanceof Expr\YieldFrom) {
return;
}

$yieldStatements[] = [$node, $scope];
};
}

/**
* @param callable(Node $node, Scope $scope): void $nodeCallback
*/
Expand Down Expand Up @@ -148,7 +357,7 @@ private function processClosureNodeInternal(
// the closure's own body may invoke it (use (&$self)): its sites must
// exist before the body is observed
if ($this->closureSignatureInference->isObserving($scope)) {
$scope = $scope->addTemplateArgumentConstraints($this->closureSignatureInference->collectSites($scope, $this->closureTypeResolver->getClosureType($scope, $expr, true, $storage)));
$scope = $scope->addTemplateArgumentConstraints($this->closureSignatureInference->collectSites($scope, $this->closureTypeResolver->getShallowClosureType($scope, $expr, $storage)));
}

$useScope = $scope;
Expand Down Expand Up @@ -228,7 +437,7 @@ private function processClosureNodeInternal(
}
$bodyNodeCallback = $byRefMode === 'local' ? new NoopNodeCallback() : $nodeCallback;

$closureScope = $scope->enterAnonymousFunction($expr, $callableParameters, $nativeCallableParameters);
$closureScope = self::enterWhereInvoked($scope->enterAnonymousFunction($expr, $callableParameters, $nativeCallableParameters), $expr);
$closureScope = $closureScope->processClosureScope($byRefEntrySource, null, $byRefUses);
$closureType = $closureScope->getAnonymousFunctionReflection();
if (!$closureType instanceof ClosureType) {
Expand Down Expand Up @@ -359,7 +568,7 @@ private function processClosureNodeInternal(
break;
}

$closureScope = $scope->enterAnonymousFunction($expr, $callableParameters, $nativeCallableParameters);
$closureScope = self::enterWhereInvoked($scope->enterAnonymousFunction($expr, $callableParameters, $nativeCallableParameters), $expr);
$closureScope = $closureScope->processClosureScope($intermediaryClosureScope, $prevScope, $byRefUses);

if ($closureScope->equals($prevScope)) {
Expand Down Expand Up @@ -605,7 +814,7 @@ public function processDeferredByRefClosureBody(
$type = $byRefEntryTypes[$use->var->name];
$byRefSource = $byRefSource->assignVariable($use->var->name, $type, $type, TrinaryLogic::createYes());
}
$closureScope = $scope->enterAnonymousFunction($expr, $parameterTypes->parameters, $parameterTypes->nativeParameters)->processClosureScope($byRefSource, null, $byRefUses);
$closureScope = self::enterWhereInvoked($scope->enterAnonymousFunction($expr, $parameterTypes->parameters, $parameterTypes->nativeParameters), $expr)->processClosureScope($byRefSource, null, $byRefUses);
$closureType = $closureScope->getAnonymousFunctionReflection();
if (!$closureType instanceof ClosureType) {
throw new ShouldNotHappenException();
Expand Down Expand Up @@ -718,7 +927,7 @@ private function resolveAssignedClosureType(Expr $rightSideExpr, Expr\Closure $e
$returnType = new NeverType();
for ($iteration = 0; $iteration < NodeScopeResolver::LOOP_SCOPE_ITERATIONS; $iteration++) {
$seed = new ClosureType($type->getParameters(), $returnType, $type->isVariadic());
$iterationType = $this->closureTypeResolver->getClosureType($scope, $expr, false, $scope->getCurrentExpressionResultStorage(), null, [$variableName => $seed]);
$iterationType = $this->getClosureType($scope, $expr, $scope->getCurrentExpressionResultStorage(), null, [$variableName => $seed]);
$nextReturnType = TypeCombinator::union($returnType, $iterationType->getReturnType());
if ($nextReturnType->equals($returnType)) {
return $iterationType;
Expand Down Expand Up @@ -770,7 +979,7 @@ private function assignByRefUses(MutatingScope $scope, MutatingScope $source, ar

/**
* The closure scope was entered with a shallow reflection (parameters +
* declared return, no body walk - see ClosureTypeResolver::getClosureType()
* declared return, no body walk - see ClosureTypeResolver::getShallowClosureType()
* with $shallow). Now that the single body walk has gathered the returns,
* build the refined ClosureType from them (no second walk) and swap it onto
* the scope the ClosureReturnStatementsNode fires with, so the return-type
Expand Down Expand Up @@ -870,13 +1079,13 @@ public function processArrowFunctionNode(
$callableParameters = $parameterTypes->parameters;
$nativeCallableParameters = $parameterTypes->nativeParameters;
[$expectedReturnType, $nativeExpectedReturnType] = $this->contextualClosureParameterResolver->resolveExpectedReturnTypes($scope, $expr, $passedToType, $nativePassedToType);
$arrowFunctionScope = $scope->enterArrowFunction($expr, $callableParameters, $nativeCallableParameters);
$arrowFunctionScope = self::enterWhereInvoked($scope->enterArrowFunction($expr, $callableParameters, $nativeCallableParameters), $expr);
if ($arrowFunctionScope->getAnonymousFunctionReflection() === null) {
throw new ShouldNotHappenException();
}

// Gather the property-assign impure points and invalidate expressions the
// arrow function type needs (mirroring ClosureTypeResolver::getClosureType()),
// arrow function type needs (mirroring getClosureType()),
// on top of the regular rule node callback, so the single body walk here
// feeds ClosureTypeResolver::buildClosureTypeForArrowFunction().
$arrowFunctionImpurePoints = [];
Expand Down
2 changes: 1 addition & 1 deletion src/Analyser/ExprHandler/FuncCallHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -1023,7 +1023,7 @@ private function resolveInvokedClosureType(NodeScopeResolver $nodeScopeResolver,
}
}

return $this->closureTypeResolver->getClosureType($creationResult->getBeforeScope(), $closure, false, $storage, new CallableType($callableParameters, new MixedType(), false));
return $this->closureProcessor->getClosureType($creationResult->getBeforeScope(), $closure, $storage, new CallableType($callableParameters, new MixedType(), false));
}

return null;
Expand Down
12 changes: 9 additions & 3 deletions src/Analyser/ExprHandler/Helper/ClosureParameterResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@
use PhpParser\Node;
use PhpParser\Node\Expr;
use PHPStan\Analyser\ClosureParameterTypes;
use PHPStan\Analyser\ClosureProcessor;
use PHPStan\Analyser\ExpressionResultStorage;
use PHPStan\Analyser\MutatingScope;
use PHPStan\Analyser\NodeScopeResolver;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\DependencyInjection\Container;
use PHPStan\Reflection\Native\NativeParameterReflection;
use PHPStan\Reflection\ParameterReflection;
use PHPStan\Turbo\ShadowedByTurboExtension;
Expand All @@ -29,9 +31,13 @@
final class ClosureParameterResolver
{

/**
* The ClosureProcessor is looked up: it resolves the parameters of the
* closures it walks through this class.
*/
public function __construct(
private Container $container,
private NodeScopeResolver $nodeScopeResolver,
private ClosureTypeResolver $closureTypeResolver,
private ContextualClosureParameterResolver $contextualClosureParameterResolver,
)
{
Expand Down Expand Up @@ -61,15 +67,15 @@ public function resolve(
* Resolves the type of an expression a callable parameter is derived from -
* either the closure/arrow function whose acceptors describe the parameters,
* or a call argument refining them. A closure/arrow function is resolved
* directly through ClosureTypeResolver (as Scope::getType() would), not by
* directly through ClosureProcessor::getClosureType() (as Scope::getType() would), not by
* processing it on demand: createCallArgsParameters() runs while that very
* closure is being processed, so on-demand processing would re-enter
* ClosureProcessor::processClosureNodeInternal() endlessly.
*/
public function resolveCallableTypeForScope(Expr $expr, MutatingScope $scope): Type
{
if ($expr instanceof Expr\Closure || $expr instanceof Expr\ArrowFunction) {
return $this->closureTypeResolver->getClosureType($scope, $expr, false, $scope->getCurrentExpressionResultStorage());
return $this->container->getByType(ClosureProcessor::class)->getClosureType($scope, $expr, $scope->getCurrentExpressionResultStorage());
}

return $this->nodeScopeResolver->readTypeOfMaybeStored($expr, $scope);
Expand Down
Loading
Loading