Repository navigation
Expand file tree
/
Copy pathContextualClosureParameterResolver.php
More file actions
245 lines (215 loc) · 8.36 KB
/
Copy pathContextualClosureParameterResolver.php
File metadata and controls
245 lines (215 loc) · 8.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
<?php declare(strict_types = 1);
namespace PHPStan\Analyser\ExprHandler\Helper;
use PhpParser\Node;
use PHPStan\Analyser\ClosureParameterTypes;
use PHPStan\Analyser\ExpressionResultStorage;
use PHPStan\Analyser\Generics\ClosureSignatureInference;
use PHPStan\Analyser\MutatingScope;
use PHPStan\Analyser\NodeScopeResolver;
use PHPStan\DependencyInjection\AutowiredService;
use PHPStan\Parser\ArrayMapArgVisitor;
use PHPStan\Parser\ArrowFunctionArgVisitor;
use PHPStan\Parser\ClosureArgVisitor;
use PHPStan\Parser\ImmediatelyInvokedClosureVisitor;
use PHPStan\Reflection\ArrayMapCallbackParameterTypes;
use PHPStan\Reflection\Native\NativeParameterReflection;
use PHPStan\Reflection\ParameterReflection;
use PHPStan\Reflection\PassedByReference;
use PHPStan\Reflection\Php\DummyParameter;
use PHPStan\Turbo\ShadowedByTurboExtension;
use PHPStan\Type\MixedType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\UnionType;
use function array_key_exists;
use function array_map;
use function count;
use function max;
/**
* Closure parameters derived from the closure's context alone - the values
* array_map() or an immediate invocation feeds it, or the callable type it is
* passed to. Needs no closure type, so ClosureTypeResolver builds parameters
* through it, while ClosureParameterResolver refines them from call arguments.
*/
#[AutowiredService]
#[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../../turbo-ext/src/ContextualClosureParameterResolver.cpp')]
final class ContextualClosureParameterResolver
{
public function __construct(
private NodeScopeResolver $nodeScopeResolver,
private ClosureSignatureInference $closureSignatureInference,
)
{
}
public function hasIntrinsicArgs(Node\Expr\Closure|Node\Expr\ArrowFunction $expr): bool
{
return $expr->getAttribute(ArrayMapArgVisitor::ATTRIBUTE_NAME) !== null
|| $expr->getAttribute(ImmediatelyInvokedClosureVisitor::ARGS_ATTRIBUTE_NAME) !== null;
}
/**
* Whether the closure's parameters are typed by what surrounds it
* syntactically - array_map() or an immediate invocation - rather than by
* a callable type it is passed to.
*/
public function hasOwnContext(Node\Expr\Closure|Node\Expr\ArrowFunction $expr): bool
{
return $this->hasIntrinsicArgs($expr)
|| $expr->getAttribute(ClosureArgVisitor::ATTRIBUTE_NAME) !== null
|| $expr->getAttribute(ArrowFunctionArgVisitor::ATTRIBUTE_NAME) !== null;
}
public function resolve(
MutatingScope $scope,
Node\Expr\Closure|Node\Expr\ArrowFunction $expr,
?ExpressionResultStorage $storage,
?Type $passedToType,
?Type $nativePassedToType,
): ClosureParameterTypes
{
$arrayMapArgs = $expr->getAttribute(ArrayMapArgVisitor::ATTRIBUTE_NAME);
$immediatelyInvokedArgs = $expr->getAttribute(ImmediatelyInvokedClosureVisitor::ARGS_ATTRIBUTE_NAME);
$intrinsicArgs = $arrayMapArgs ?? $immediatelyInvokedArgs;
if ($intrinsicArgs === null) {
if ($passedToType === null && !$this->hasOwnContext($expr)) {
// nothing types the closure where it is written: the second pass
// of the enclosing body walks it with what its usages resolved
return new ClosureParameterTypes(
$this->closureSignatureInference->getBodyParameters($scope, $expr),
null,
);
}
return new ClosureParameterTypes(
$this->createPassedToTypeParameters($scope, $passedToType),
$this->createPassedToTypeParameters($scope, $nativePassedToType),
);
}
$types = [];
$nativeTypes = [];
$arrayTypes = [];
$nativeArrayTypes = [];
$hasUnpackedArg = false;
foreach ($intrinsicArgs as $arg) {
$hasUnpackedArg = $hasUnpackedArg || $arg->unpack;
$result = $storage !== null ? $storage->findExpressionResult($arg->value) : null;
$type = $result !== null ? $result->getType() : $this->nodeScopeResolver->readScopeStateOrSyntheticType($arg->value, $scope);
$nativeType = $result !== null ? $result->getNativeType() : $this->nodeScopeResolver->readScopeStateOrSyntheticType($arg->value, $scope->doNotTreatPhpDocTypesAsCertain());
if ($arrayMapArgs !== null) {
$arrayTypes[] = $type;
$nativeArrayTypes[] = $nativeType;
$type = $type->getIterableValueType();
$nativeType = $nativeType->getIterableValueType();
}
$types[] = $type;
$nativeTypes[] = $nativeType;
}
// an unpacked arg is one parameter here, so its arrays cannot be told apart
if ($arrayMapArgs !== null && !$hasUnpackedArg) {
$types = ArrayMapCallbackParameterTypes::addPaddingNull($types, $arrayTypes);
$nativeTypes = ArrayMapCallbackParameterTypes::addPaddingNull($nativeTypes, $nativeArrayTypes);
}
$parameters = [];
foreach ($types as $type) {
$parameters[] = new DummyParameter('item', $type, optional: false, passedByReference: PassedByReference::createNo(), variadic: false, defaultValue: null);
}
$nativeParameters = [];
foreach ($nativeTypes as $nativeType) {
$nativeParameters[] = new DummyParameter('item', $nativeType, optional: false, passedByReference: PassedByReference::createNo(), variadic: false, defaultValue: null);
}
return new ClosureParameterTypes($parameters, $nativeParameters);
}
/**
* The types the closure's returned expressions are expected to have: the
* return type of the callable it is passed to, or - for a closure nothing
* types where it is written - the return type of the callables its value is
* sent to later (see ClosureSignatureInference).
*
* @return array{Type|null, Type|null}
*/
public function resolveExpectedReturnTypes(
MutatingScope $scope,
Node\Expr\Closure|Node\Expr\ArrowFunction $expr,
?Type $passedToType,
?Type $nativePassedToType,
): array
{
if ($this->hasOwnContext($expr)) {
return [null, null];
}
if ($passedToType === null) {
return [$this->closureSignatureInference->getExpectedReturnType($scope, $expr), null];
}
return [
$this->createPassedToTypeReturnType($scope, $passedToType),
$this->createPassedToTypeReturnType($scope, $nativePassedToType),
];
}
private function createPassedToTypeReturnType(MutatingScope $scope, ?Type $passedToType): ?Type
{
if ($passedToType === null || $passedToType->isCallable()->no()) {
return null;
}
if ($passedToType instanceof UnionType) {
$passedToType = $passedToType->filterTypes(static fn (Type $innerType) => $innerType->isCallable()->yes());
if ($passedToType->isCallable()->no()) {
return null;
}
}
$returnTypes = [];
foreach ($passedToType->getCallableParametersAcceptors($scope) as $acceptor) {
$returnType = $acceptor->getReturnType();
if ($returnType instanceof MixedType || $returnType->isVoid()->yes() || $returnType->hasTemplateOrLateResolvableType()) {
return null;
}
$returnTypes[] = $returnType;
}
if ($returnTypes === []) {
return null;
}
return TypeCombinator::union(...$returnTypes);
}
/**
* @return ParameterReflection[]|null
*/
private function createPassedToTypeParameters(MutatingScope $scope, ?Type $passedToType): ?array
{
if ($passedToType === null || $passedToType->isCallable()->no()) {
return null;
}
if ($passedToType instanceof UnionType) {
$passedToType = $passedToType->filterTypes(static fn (Type $innerType) => $innerType->isCallable()->yes());
if ($passedToType->isCallable()->no()) {
return null;
}
}
$callableParameters = null;
$acceptors = $passedToType->getCallableParametersAcceptors($scope);
foreach ($acceptors as $acceptor) {
$acceptorParameters = array_map(static fn (ParameterReflection $callableParameter) => new NativeParameterReflection(
$callableParameter->getName(),
$callableParameter->isOptional(),
$callableParameter->getType(),
$callableParameter->passedByReference(),
$callableParameter->isVariadic(),
$callableParameter->getDefaultValue(),
), $acceptor->getParameters());
if ($callableParameters === null) {
$callableParameters = $acceptorParameters;
continue;
}
$newParameters = [];
$parameterCount = max(count($callableParameters), count($acceptorParameters));
for ($i = 0; $i < $parameterCount; $i++) {
if (!array_key_exists($i, $acceptorParameters)) {
$newParameters[] = $callableParameters[$i]->toOptional();
continue;
}
if (!array_key_exists($i, $callableParameters)) {
$newParameters[] = $acceptorParameters[$i]->toOptional();
continue;
}
$newParameters[] = $callableParameters[$i]->union($acceptorParameters[$i]);
}
$callableParameters = $newParameters;
}
return $callableParameters;
}
}