Skip to content

Commit a6b862e

Browse files
ondrejmirtesclaude
andcommitted
Walk an immediately invoked closure's arguments before the callee
An immediately invoked closure's untyped parameters take the types of its invocation arguments, which the closure type resolver read from the scope ahead of their walk - the last processSyntheticOnDemand() seam under the new-world guard (and, for the pipe operator, the callee was evaluated before its operand, unlike PHP). The call handler now walks the arguments first, on the closure's declared signature (ClosureTypeResolver::getDeclaredClosureType(), the signature without invocation inference or a body walk), then the closure, whose parameter inference consumes the stored argument results; the call resolves from the walked closure's acceptor over the same processed arguments (ArgsResult::withResolvedParametersAcceptor()). The closure is thereby walked on the post-argument scope: a by-value use of a variable an argument assigns sees the assigned value. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01R7pqAkCx4xP6WYxBo2nMJE
1 parent be01378 commit a6b862e

3 files changed

Lines changed: 75 additions & 33 deletions

File tree

‎src/Analyser/ArgsResult.php‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,19 @@ public function getImpurePoints(): array
103103
return $this->expressionResult->getImpurePoints();
104104
}
105105

106+
/**
107+
* The same processed arguments under another acceptor: an immediately
108+
* invoked closure's arguments are walked on its declared signature, the
109+
* acceptor the call resolves from is the walked closure's.
110+
*/
111+
public function withResolvedParametersAcceptor(?ParametersAcceptor $resolvedParametersAcceptor): self
112+
{
113+
$clone = clone $this;
114+
$clone->resolvedParametersAcceptor = $resolvedParametersAcceptor;
115+
116+
return $clone;
117+
}
118+
106119
public function getResolvedParametersAcceptor(): ?ParametersAcceptor
107120
{
108121
return $this->resolvedParametersAcceptor;

‎src/Analyser/ExprHandler/FuncCallHandler.php‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
use PHPStan\Analyser\ExpressionResultFactory;
2020
use PHPStan\Analyser\ExpressionResultStorage;
2121
use PHPStan\Analyser\ExprHandler;
22+
use PHPStan\Analyser\ExprHandler\Helper\ClosureTypeResolver;
2223
use PHPStan\Analyser\ExprHandler\Helper\DefaultNarrowingHelper;
2324
use PHPStan\Analyser\ExprHandler\Helper\DynamicReturnTypeStoragePrimer;
2425
use PHPStan\Analyser\ExprHandler\Helper\EarlyTerminatingCallHelper;
@@ -38,6 +39,7 @@
3839
use PHPStan\DependencyInjection\ExtensionsCollection;
3940
use PHPStan\Node\ClosureReturnStatementsNode;
4041
use PHPStan\Node\Expr\TypeExpr;
42+
use PHPStan\Parser\ImmediatelyInvokedClosureVisitor;
4143
use PHPStan\Reflection\Callables\CallableParametersAcceptor;
4244
use PHPStan\Reflection\Callables\SimpleImpurePoint;
4345
use PHPStan\Reflection\Callables\SimpleThrowPoint;
@@ -97,6 +99,7 @@ public function __construct(
9799
private EarlyTerminatingCallHelper $earlyTerminatingHelper,
98100
private DynamicReturnTypeStoragePrimer $storagePrimer,
99101
private ImpossibleCheckTypeHelper $impossibleCheckTypeHelper,
102+
private ClosureTypeResolver $closureTypeResolver,
100103
)
101104
{
102105
}
@@ -122,6 +125,21 @@ public function processExpr(NodeScopeResolver $nodeScopeResolver, Stmt $stmt, Ex
122125
$isEarlyTerminating = $expr->name instanceof Name
123126
&& $this->earlyTerminatingHelper->isEarlyTerminatingFunctionCall($expr->name->toString());
124127
$isAlwaysTerminating = $isEarlyTerminating;
128+
$argumentsWalkedAhead = null;
129+
if (
130+
($expr->name instanceof Expr\Closure || $expr->name instanceof Expr\ArrowFunction)
131+
&& $expr->name->getAttribute(ImmediatelyInvokedClosureVisitor::ARGS_ATTRIBUTE_NAME) !== null
132+
) {
133+
// An immediately invoked closure's untyped parameters take the types
134+
// of its invocation arguments, so the arguments are walked BEFORE the
135+
// callee - on the closure's declared signature - and the closure body
136+
// consumes their stored results instead of pricing them ahead of
137+
// their turn. The closure is then walked on the post-argument scope.
138+
$shallowVariants = $this->closureTypeResolver->getDeclaredClosureType($scope, $expr->name)->getCallableParametersAcceptors($scope);
139+
$shallowAcceptor = ParametersAcceptorSelector::combineVariantsForNormalization($expr->getArgs(), $shallowVariants, null);
140+
$argumentsWalkedAhead = $nodeScopeResolver->processArgs($stmt, null, null, $shallowVariants, null, ArgumentsNormalizer::reorderFuncArguments($shallowAcceptor, $expr) ?? $expr, $scope, $storage, $nodeCallback, $context);
141+
$scope = $argumentsWalkedAhead->getScope();
142+
}
125143
if ($expr->name instanceof Expr) {
126144
// process the dynamic callee name first, then consume its type (single-pass
127145
// inside-out) rather than reading it before processExprNode() stores it

‎src/Analyser/ExprHandler/Helper/ClosureTypeResolver.php‎

Lines changed: 44 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@
3737
use PHPStan\ShouldNotHappenException;
3838
use PHPStan\TrinaryLogic;
3939
use PHPStan\Type\ClosureType;
40-
use PHPStan\Type\ErrorType;
4140
use PHPStan\Type\Generic\GenericObjectType;
4241
use PHPStan\Type\Generic\TemplateTypeMap;
4342
use PHPStan\Type\Generic\TemplateTypeVarianceMap;
@@ -735,16 +734,12 @@ private function deriveOnlyNeverExecutionEnds(array $executionEnds): ?bool
735734
}
736735

737736
/**
738-
* Builds the closure/arrow function's declared parameters (independent of the
739-
* body walk) and the callable parameter acceptors derived from the call site.
737+
* The declared signature's parameters, independent of the body walk and of
738+
* the call site.
740739
*
741-
* @return array{list<NativeParameterReflection>, bool, ParameterReflection[]|null, ParameterReflection[]|null}
740+
* @return array{list<NativeParameterReflection>, bool}
742741
*/
743-
private function buildParametersAndAcceptors(
744-
MutatingScope $scope,
745-
Node\Expr\Closure|ArrowFunction $expr,
746-
?ExpressionResultStorage $storage = null,
747-
): array
742+
private function buildDeclaredParameters(MutatingScope $scope, Node\Expr\Closure|ArrowFunction $expr): array
748743
{
749744
$parameters = [];
750745
$isVariadic = false;
@@ -782,6 +777,41 @@ private function buildParametersAndAcceptors(
782777
);
783778
}
784779

780+
return [$parameters, $isVariadic];
781+
}
782+
783+
/**
784+
* The closure's declared signature: the parameters as written plus the
785+
* DECLARED return type - no invocation-argument inference, no body walk.
786+
* The call handler walks an immediately invoked closure's arguments on it
787+
* before the closure itself, whose untyped parameters they then type.
788+
*/
789+
public function getDeclaredClosureType(MutatingScope $scope, Node\Expr\Closure|ArrowFunction $expr): ClosureType
790+
{
791+
[$parameters, $isVariadic] = $this->buildDeclaredParameters($scope, $expr);
792+
793+
return new ClosureType(
794+
$parameters,
795+
$scope->getFunctionType($expr->returnType, false, false),
796+
$isVariadic,
797+
isStatic: TrinaryLogic::createFromBoolean($expr->static),
798+
);
799+
}
800+
801+
/**
802+
* Builds the closure/arrow function's declared parameters (independent of the
803+
* body walk) and the callable parameter acceptors derived from the call site.
804+
*
805+
* @return array{list<NativeParameterReflection>, bool, ParameterReflection[]|null, ParameterReflection[]|null}
806+
*/
807+
private function buildParametersAndAcceptors(
808+
MutatingScope $scope,
809+
Node\Expr\Closure|ArrowFunction $expr,
810+
?ExpressionResultStorage $storage = null,
811+
): array
812+
{
813+
[$parameters, $isVariadic] = $this->buildDeclaredParameters($scope, $expr);
814+
785815
$callableParameters = null;
786816
$nativeCallableParameters = null;
787817
$arrayMapArgs = $expr->getAttribute(ArrayMapArgVisitor::ATTRIBUTE_NAME);
@@ -797,31 +827,12 @@ private function buildParametersAndAcceptors(
797827
}
798828
} elseif ($immediatelyInvokedArgs !== null) {
799829
foreach ($immediatelyInvokedArgs as $immediatelyInvokedArg) {
800-
// an immediately invoked closure is the callee: its invocation
801-
// arguments are walked AFTER the closure itself, so there is no
802-
// stored result yet. Constants price through the initializer
803-
// resolver and plain variables read scope state by name; the
804-
// ask-ahead-of-walk scope read remains the seam for the rest.
830+
// an immediately invoked closure is the callee; the call handler
831+
// walks its invocation arguments BEFORE the closure, so their
832+
// results are stored (see FuncCallHandler)
805833
$argValue = $immediatelyInvokedArg->value;
806-
if (
807-
$argValue instanceof Node\Scalar\String_
808-
|| $argValue instanceof Node\Scalar\Int_
809-
|| $argValue instanceof Node\Scalar\Float_
810-
|| ($argValue instanceof Node\Expr\ClassConstFetch && $argValue->class instanceof Node\Name && $argValue->name instanceof Node\Identifier)
811-
|| $argValue instanceof Node\Expr\ConstFetch
812-
) {
813-
$argType = $this->initializerExprTypeResolver->getType($argValue, InitializerExprContext::fromScope($scope));
814-
$argNativeType = $argType;
815-
} elseif ($argValue instanceof Node\Expr\Variable && is_string($argValue->name)) {
816-
$argType = $scope->hasVariableType($argValue->name)->no() ? new ErrorType() : $scope->getVariableType($argValue->name);
817-
$nativeScope = $scope->doNotTreatPhpDocTypesAsCertain();
818-
$argNativeType = $nativeScope->hasVariableType($argValue->name)->no() ? new ErrorType() : $nativeScope->getVariableType($argValue->name);
819-
} else {
820-
$argType = $scope->getType($argValue);
821-
$argNativeType = $scope->getNativeType($argValue);
822-
}
823-
$callableParameters[] = new DummyParameter('item', $argType, optional: false, passedByReference: PassedByReference::createNo(), variadic: false, defaultValue: null);
824-
$nativeCallableParameters[] = new DummyParameter('item', $argNativeType, optional: false, passedByReference: PassedByReference::createNo(), variadic: false, defaultValue: null);
834+
$callableParameters[] = new DummyParameter('item', $this->readExprType($storage, $argValue, $scope, false), optional: false, passedByReference: PassedByReference::createNo(), variadic: false, defaultValue: null);
835+
$nativeCallableParameters[] = new DummyParameter('item', $this->readExprType($storage, $argValue, $scope->doNotTreatPhpDocTypesAsCertain(), true), optional: false, passedByReference: PassedByReference::createNo(), variadic: false, defaultValue: null);
825836
}
826837
} else {
827838
$inFunctionCallsStackCount = count($scope->inFunctionCallsStack);

0 commit comments

Comments
 (0)