1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Reflection;
4:
5: use PHPStan\Analyser\OutOfClassScope;
6: use PHPStan\PhpDoc\Tag\TemplateTag;
7: use PHPStan\Reflection\Callables\CallableParametersAcceptor;
8: use PHPStan\Reflection\Native\NativeParameterReflection;
9: use PHPStan\Reflection\Php\ExtendedDummyParameter;
10: use PHPStan\TrinaryLogic;
11: use PHPStan\Turbo\ReferencedByTurboExtension;
12: use PHPStan\Type\CallableAssertionsHelper;
13: use PHPStan\Type\CallableType;
14: use PHPStan\Type\ClosureType;
15: use PHPStan\Type\ConditionalTypeForParameter;
16: use PHPStan\Type\ErrorType;
17: use PHPStan\Type\Generic\TemplateType;
18: use PHPStan\Type\Generic\TemplateTypeFactory;
19: use PHPStan\Type\Generic\TemplateTypeHelper;
20: use PHPStan\Type\Generic\TemplateTypeMap;
21: use PHPStan\Type\Generic\TemplateTypeVariance;
22: use PHPStan\Type\Generic\TemplateTypeVarianceMap;
23: use PHPStan\Type\MixedType;
24: use PHPStan\Type\NeverType;
25: use PHPStan\Type\Type;
26: use PHPStan\Type\TypeCombinator;
27: use PHPStan\Type\TypeTraverser;
28: use PHPStan\Type\UnionType;
29: use function array_diff_key;
30: use function array_intersect_key;
31: use function array_key_exists;
32: use function array_keys;
33: use function array_last;
34: use function array_map;
35: use function array_merge;
36: use function count;
37: use function is_int;
38:
39: #[ReferencedByTurboExtension(key: 'genericParametersAcceptorResolver')]
40: final class GenericParametersAcceptorResolver
41: {
42:
43: /**
44: * The parameter with the templates that the sibling argument types
45: * determine resolved, for typing a closure passed to it before its own
46: * type is known. A template that also occurs in a non-covariant position
47: * of the parameter (the T in callable(T): T, an accumulator) is fed by
48: * the closure's own return, so it stays unresolved unless
49: * $accumulatorTypes holds a round of its fixed point
50: * (see resolveAccumulatorTemplateTypes()).
51: *
52: * @param array<int|string, Type> $siblingTypes
53: * @param array<string, Type> $accumulatorTypes
54: */
55: public static function resolveParameterFromSiblings(array $siblingTypes, ParametersAcceptor $parametersAcceptor, ParameterReflection $parameter, array $accumulatorTypes = []): ParameterReflection
56: {
57: $parameterType = $parameter->getType();
58: if (!$parameterType->hasTemplateOrLateResolvableType()) {
59: return $parameter;
60: }
61:
62: $siblingTemplateTypes = [];
63: foreach (self::resolve($siblingTypes, $parametersAcceptor)->getResolvedTemplateTypeMap()->getTypes() as $name => $type) {
64: if ($type instanceof ErrorType) {
65: continue;
66: }
67: $siblingTemplateTypes[$name] = $type;
68: }
69: foreach ($parameterType->getReferencedTemplateTypes(TemplateTypeVariance::createContravariant()) as $reference) {
70: if ($reference->getPositionVariance()->covariant()) {
71: continue;
72: }
73: unset($siblingTemplateTypes[$reference->getType()->getName()]);
74: }
75: $siblingTemplateTypes = array_merge($siblingTemplateTypes, $accumulatorTypes);
76: if ($siblingTemplateTypes === []) {
77: return $parameter;
78: }
79:
80: $parameterType = TemplateTypeHelper::resolveTemplateTypes($parameterType, new TemplateTypeMap($siblingTemplateTypes), TemplateTypeVarianceMap::createEmpty(), TemplateTypeVariance::createContravariant());
81:
82: return new ExtendedDummyParameter(
83: $parameter->getName(),
84: $parameterType,
85: $parameter->isOptional(),
86: $parameter->passedByReference(),
87: $parameter->isVariadic(),
88: $parameter->getDefaultValue(),
89: $parameter instanceof ExtendedParameterReflection ? $parameter->getNativeType() : new MixedType(),
90: $parameterType,
91: null,
92: TrinaryLogic::createMaybe(),
93: null,
94: [],
95: null,
96: TrinaryLogic::createNo(),
97: TrinaryLogic::createNo(),
98: );
99: }
100:
101: /**
102: * The templates a callable parameter passes to the closure given for it
103: * (the T in callable(T): U) and the templates it receives back from it
104: * (the U), as two sets of template names.
105: *
106: * @return array{array<string, true>, array<string, true>}
107: */
108: public static function getCallableTemplateFlow(ParameterReflection $parameter): array
109: {
110: $parameterType = $parameter->getType();
111: if (!$parameterType->hasTemplateOrLateResolvableType()) {
112: return [[], []];
113: }
114:
115: $passed = [];
116: $returned = [];
117: foreach ($parameterType->getReferencedTemplateTypes(TemplateTypeVariance::createContravariant()) as $reference) {
118: $name = $reference->getType()->getName();
119: if ($reference->getPositionVariance()->covariant()) {
120: $passed[$name] = true;
121: } else {
122: $returned[$name] = true;
123: }
124: }
125:
126: return [$passed, $returned];
127: }
128:
129: /**
130: * The accumulators - templates that callable parameters pass to their
131: * closures and receive back from them, as the TCarry in
132: * callable(TCarry, T): TCarry, or the T and U of callable(T): U and
133: * callable(U): T together (see getCallableTemplateFlow()) - each with the
134: * type the argument types determine. Without the closures among $argTypes
135: * this is the seed of the accumulators' fixed point, with the closures
136: * typed by the previous round it is the next round. An accumulator the
137: * arguments do not determine is left out.
138: *
139: * @param array<int|string, Type> $argTypes
140: * @param array<string, true> $accumulators
141: * @return array<string, Type>
142: */
143: public static function resolveAccumulatorTemplateTypes(array $argTypes, ParametersAcceptor $parametersAcceptor, array $accumulators): array
144: {
145: if ($accumulators === []) {
146: return [];
147: }
148:
149: $resolvedTemplateTypeMap = self::resolve($argTypes, $parametersAcceptor)->getResolvedTemplateTypeMap();
150: $types = [];
151: foreach (array_keys($accumulators) as $name) {
152: $type = $resolvedTemplateTypeMap->getType($name);
153: if ($type === null || $type instanceof ErrorType) {
154: continue;
155: }
156: $types[$name] = self::isUnresolvableAccumulatorType($type, $parametersAcceptor->getTemplateTypeMap()) ? new MixedType() : $type;
157: }
158:
159: return $types;
160: }
161:
162: /**
163: * An accumulator type with an error type, from a closure body that does
164: * not type with the accumulator, or with a template of the called
165: * function itself, which a closure parameter the arguments leave
166: * unresolved returns, cannot be resolved further: it widens to mixed.
167: */
168: private static function isUnresolvableAccumulatorType(Type $type, TemplateTypeMap $calleeTemplateTypeMap): bool
169: {
170: $unresolvable = false;
171: TypeTraverser::map($type, static function (Type $type, callable $traverse) use ($calleeTemplateTypeMap, &$unresolvable): Type {
172: if ($type instanceof ErrorType) {
173: $unresolvable = true;
174: } elseif ($type instanceof TemplateType) {
175: $calleeTemplateType = $calleeTemplateTypeMap->getType($type->getName());
176: if ($calleeTemplateType instanceof TemplateType && $calleeTemplateType->getScope()->equals($type->getScope())) {
177: $unresolvable = true;
178: }
179: }
180:
181: return $unresolvable ? $type : $traverse($type);
182: });
183:
184: return $unresolvable;
185: }
186:
187: /**
188: * @api
189: * @param array<int|string, Type> $argTypes
190: */
191: public static function resolve(array $argTypes, ParametersAcceptor $parametersAcceptor): ExtendedParametersAcceptor
192: {
193: $typeMap = TemplateTypeMap::createEmpty();
194: $passedArgs = [];
195:
196: $parameters = $parametersAcceptor->getParameters();
197: $namedArgTypes = [];
198: foreach ($argTypes as $i => $argType) {
199: if (is_int($i)) {
200: if (isset($parameters[$i])) {
201: if ($parameters[$i]->getName() === '') {
202: $parameters = self::nameParameters($parameters);
203: }
204: $namedArgTypes[$parameters[$i]->getName()] = $argType;
205: continue;
206: }
207: if (count($parameters) > 0) {
208: $lastParameter = array_last($parameters);
209: if ($lastParameter->isVariadic()) {
210: $parameterName = $lastParameter->getName();
211: if (array_key_exists($parameterName, $namedArgTypes)) {
212: $namedArgTypes[$parameterName] = TypeCombinator::union($namedArgTypes[$parameterName], $argType);
213: continue;
214: }
215: $namedArgTypes[$parameterName] = $argType;
216: }
217: }
218: continue;
219: }
220:
221: $namedArgTypes[$i] = $argType;
222: }
223:
224: // type predicates of passed callables determine their template types exactly,
225: // so they are inferred first and substituted into the parameter types —
226: // the remaining template types are then inferred from what is left over,
227: // e.g. in partition(iterable<T0|T1> $values, callable(T0|T1): ($value is T0 ? true : false) $predicate)
228: // called with iterable<int|string> and is_int(...), T0 becomes int and T1 string
229: // null when no passed callable has a type predicate, which is almost always
230: $predicateTypeMap = null;
231: $callableParameters = [];
232: foreach ($parameters as $param) {
233: $paramName = $param->getName();
234: if (!isset($namedArgTypes[$paramName])) {
235: continue;
236: }
237:
238: $paramType = $param->getType();
239: $argType = $namedArgTypes[$paramName];
240: // a bare template like the T of T $x, the common case, is no callable with parameters
241: if (!$paramType instanceof TemplateType && !$argType->isCallable()->no()) {
242: $callableParameters[] = $param;
243: }
244:
245: $paramPredicateTypeMap = self::inferPredicateTemplateTypes($paramType, $argType);
246: if ($paramPredicateTypeMap === null || $paramPredicateTypeMap->isEmpty()) {
247: continue;
248: }
249:
250: $predicateTypeMap = $predicateTypeMap === null ? $paramPredicateTypeMap : $predicateTypeMap->union($paramPredicateTypeMap);
251: }
252:
253: // null when no generic callable like identity(...) is passed for a callable parameter, which is almost always
254: $genericCallables = $callableParameters === [] ? null : self::instantiateGenericCallables($callableParameters, $namedArgTypes, $parametersAcceptor);
255: $genericCallableTypeMaps = $genericCallables === null ? [] : $genericCallables[0];
256:
257: // null when no parameter has a conditional type, which is almost always
258: $conditionalInference = self::createConditionalInference($parameters, $namedArgTypes, $parametersAcceptor->getTemplateTypeMap());
259: if ($conditionalInference !== null) {
260: // conditions on later parameters are decided by their arguments, so all of them are known up front
261: foreach ($parameters as $param) {
262: $argType = self::getArgType($param, $namedArgTypes);
263: if ($argType === null) {
264: continue;
265: }
266:
267: $passedArgs['$' . $param->getName()] = $argType;
268: }
269: }
270:
271: /** @var array<string, list<Type>> $pinnedTypes */
272: $pinnedTypes = [];
273: foreach ($conditionalInference === null ? $parameters : $conditionalInference->order() as $param) {
274: $argType = self::getArgType($param, $namedArgTypes);
275: if ($argType === null) {
276: continue;
277: }
278:
279: $paramName = $param->getName();
280: $passedArgs['$' . $paramName] = $argType;
281: $paramType = $predicateTypeMap === null ? $param->getType() : self::resolvePredicateTemplateTypes($param->getType(), $predicateTypeMap);
282: $paramTypeMap = $genericCallableTypeMaps[$paramName] ?? ($conditionalInference === null ? $paramType->inferTemplateTypes($argType) : ConditionalParameterTypeInference::inferTemplateTypes($paramType, $argType));
283: if ($conditionalInference !== null) {
284: $decidedParamType = $conditionalInference->resolve($paramName, $paramType, $passedArgs, $typeMap);
285: if ($decidedParamType !== $paramType) {
286: $paramTypeMap = ConditionalParameterTypeInference::inferFromDecided($decidedParamType, $argType, $paramTypeMap);
287: $paramType = $decidedParamType;
288: }
289: }
290: $typeMap = $typeMap->union($paramTypeMap);
291: // a bare template refers only to itself, in the parameter's contravariant position, so it never pins
292: if (!$paramType instanceof TemplateType) {
293: $pinnedTypes = self::collectPinnedTemplateTypes($paramType, $paramTypeMap, $pinnedTypes);
294: }
295: // otherwise the last map stays alive until the end of resolve() and raises its peak memory
296: unset($paramTypeMap);
297: }
298:
299: if ($predicateTypeMap !== null) {
300: $typeMap = $typeMap->union($predicateTypeMap);
301: }
302:
303: $returnType = $parametersAcceptor->getReturnType();
304: if (
305: $returnType instanceof ConditionalTypeForParameter
306: && !$returnType->isNegated()
307: && array_key_exists($returnType->getParameterName(), $passedArgs)
308: ) {
309: $paramType = $predicateTypeMap === null ? $returnType->getTarget() : self::resolvePredicateTemplateTypes($returnType->getTarget(), $predicateTypeMap);
310: $argType = $passedArgs[$returnType->getParameterName()];
311: // the condition binds only the templates the parameters say nothing about, as T in
312: // `($id is class-string<T> ? T : mixed)`; T inferred from `T $t` is not widened by
313: // what the argument for the condition is, or `($x is T ? …)` would always hold
314: $conditionTypeMap = $paramType->inferTemplateTypes($argType);
315: foreach (array_keys($typeMap->getTypes()) as $name) {
316: $conditionTypeMap = $conditionTypeMap->unsetType($name);
317: }
318: $typeMap = $typeMap->union($conditionTypeMap);
319: }
320:
321: $resolvedTemplateTypeMap = new TemplateTypeMap(array_merge(
322: $parametersAcceptor->getTemplateTypeMap()->map(static fn (string $name, Type $type): Type => new ErrorType())->getTypes(),
323: $typeMap->getTypes(),
324: $pinnedTypes === [] ? [] : self::resolvePinnedTemplateTypes($pinnedTypes),
325: self::resolveContravariantReturnTemplateTypes($returnType, $typeMap->getUpperBoundTypes()),
326: ));
327:
328: $originalParametersAcceptor = $parametersAcceptor;
329:
330: if (!$parametersAcceptor instanceof ExtendedParametersAcceptor) {
331: $parametersAcceptor = new ExtendedFunctionVariant(
332: $parametersAcceptor->getTemplateTypeMap(),
333: $parametersAcceptor->getResolvedTemplateTypeMap(),
334: array_map(static fn (ParameterReflection $parameter): ExtendedParameterReflection => new ExtendedDummyParameter(
335: $parameter->getName(),
336: $parameter->getType(),
337: $parameter->isOptional(),
338: $parameter->passedByReference(),
339: $parameter->isVariadic(),
340: $parameter->getDefaultValue(),
341: new MixedType(),
342: $parameter->getType(),
343: null,
344: TrinaryLogic::createMaybe(),
345: null,
346: [],
347: null,
348: TrinaryLogic::createNo(),
349: TrinaryLogic::createNo(),
350: ), $parametersAcceptor->getParameters()),
351: $parametersAcceptor->isVariadic(),
352: $returnType,
353: $returnType,
354: new MixedType(),
355: TemplateTypeVarianceMap::createEmpty(),
356: );
357: }
358:
359: if ($genericCallables !== null && $genericCallables[1] !== []) {
360: [$parametersAcceptor, $resolvedTemplateTypeMap] = self::bindFreeTemplateTypes($parametersAcceptor, $resolvedTemplateTypeMap, $genericCallables[1]);
361: }
362:
363: $result = new ResolvedFunctionVariantWithOriginal(
364: $parametersAcceptor,
365: $resolvedTemplateTypeMap,
366: $parametersAcceptor->getCallSiteVarianceMap(),
367: $passedArgs,
368: );
369: if ($originalParametersAcceptor instanceof CallableParametersAcceptor) {
370: return new ResolvedFunctionVariantWithCallable(
371: $result,
372: $originalParametersAcceptor->getThrowPoints(),
373: $originalParametersAcceptor->isPure(),
374: $originalParametersAcceptor->getImpurePoints(),
375: $originalParametersAcceptor->getInvalidateExpressions(),
376: $originalParametersAcceptor->getUsedVariables(),
377: $originalParametersAcceptor->acceptsNamedArguments(),
378: $originalParametersAcceptor->mustUseReturnValue(),
379: $originalParametersAcceptor->getAsserts(),
380: $originalParametersAcceptor->isStaticClosure(),
381: );
382: }
383:
384: return $result;
385: }
386:
387: /**
388: * A generic callable like identity(...) passed for a callable parameter that
389: * mentions the called function's templates, like callable(A): B, is
390: * instantiated in the context of the parameter, not with the templates
391: * themselves (that would leak A out of the call): its templates take the
392: * types the parameter's parameters (and return type) get from the other
393: * arguments, and those the arguments say nothing about stay its own, free
394: * for the result to bind - compose(toList(...), box(...)) is
395: * Closure<T>(T): array{boxed: list<T>}. TypeScript calls this higher order
396: * function type inference.
397: *
398: * Returns what each such argument infers by parameter name and the free
399: * templates by name, renamed apart from the called function's templates
400: * and from the ones the arguments mention.
401: *
402: * @param list<ParameterReflection> $callableParameters the parameters given a callable argument
403: * @param array<string, Type> $namedArgTypes
404: * @return array{array<string, TemplateTypeMap>, array<string, TemplateType>}|null null when no such argument is passed
405: */
406: private static function instantiateGenericCallables(array $callableParameters, array $namedArgTypes, ParametersAcceptor $parametersAcceptor): ?array
407: {
408: $calleeTemplateTypeMap = $parametersAcceptor->getTemplateTypeMap();
409: if ($calleeTemplateTypeMap->isEmpty()) {
410: return null;
411: }
412:
413: $genericCallables = [];
414: foreach ($callableParameters as $param) {
415: $paramName = $param->getName();
416: $paramType = $param->getType();
417: if (!$paramType->hasTemplateOrLateResolvableType() || $paramType->isCallable()->no()) {
418: continue;
419: }
420:
421: $argAcceptors = $namedArgTypes[$paramName]->getCallableParametersAcceptors(new OutOfClassScope());
422: if (
423: count($argAcceptors) !== 1
424: || $argAcceptors[0]->getTemplateTypeMap()->isEmpty()
425: || !$argAcceptors[0]->getResolvedTemplateTypeMap()->isEmpty()
426: ) {
427: continue;
428: }
429:
430: $paramAcceptors = $paramType->getCallableParametersAcceptors(new OutOfClassScope());
431: if (count($paramAcceptors) !== 1) {
432: continue;
433: }
434:
435: $genericCallables[$paramName] = [$paramType, $paramAcceptors[0], $argAcceptors[0]];
436: }
437:
438: if ($genericCallables === []) {
439: return null;
440: }
441:
442: $scope = new OutOfClassScope();
443: $usedNames = [];
444: foreach (array_keys($calleeTemplateTypeMap->getTypes()) as $name) {
445: $usedNames[$name] = true;
446: }
447: foreach ($namedArgTypes as $paramName => $argType) {
448: $ownTemplateTypeMap = isset($genericCallables[$paramName]) ? $genericCallables[$paramName][2]->getTemplateTypeMap() : TemplateTypeMap::createEmpty();
449: foreach ($argType->getReferencedTemplateTypes(TemplateTypeVariance::createCovariant()) as $reference) {
450: if (self::isTemplateTypeOf($reference->getType(), $ownTemplateTypeMap)) {
451: continue;
452: }
453:
454: $usedNames[$reference->getType()->getName()] = true;
455: }
456: }
457:
458: $contextTypes = [];
459: $siblingArgTypes = array_diff_key($namedArgTypes, $genericCallables);
460: if ($siblingArgTypes !== []) {
461: foreach (self::resolve($siblingArgTypes, $parametersAcceptor)->getResolvedTemplateTypeMap()->getTypes() as $name => $type) {
462: if ($type instanceof ErrorType) {
463: continue;
464: }
465:
466: $contextTypes[$name] = $type;
467: }
468: }
469:
470: $typeMaps = [];
471: $freeTemplateTypes = [];
472: foreach ($genericCallables as $paramName => [$paramType, $paramAcceptor, $argAcceptor]) {
473: $contextAcceptor = TemplateTypeHelper::resolveTemplateTypes(
474: $paramType,
475: new TemplateTypeMap($contextTypes),
476: TemplateTypeVarianceMap::createEmpty(),
477: TemplateTypeVariance::createContravariant(),
478: )->getCallableParametersAcceptors($scope)[0];
479:
480: $contextParameterTypes = [];
481: foreach ($contextAcceptor->getParameters() as $i => $contextParameter) {
482: if (self::referencesTemplateTypeOf($contextParameter->getType(), $calleeTemplateTypeMap)) {
483: continue;
484: }
485:
486: $contextParameterTypes[$i] = $contextParameter->getType();
487: }
488:
489: $ownTypes = [];
490: foreach (self::resolve($contextParameterTypes, $argAcceptor)->getResolvedTemplateTypeMap()->getTypes() as $name => $type) {
491: if ($type instanceof ErrorType) {
492: continue;
493: }
494:
495: $ownTypes[$name] = $type;
496: }
497:
498: // a template the parameters leave open takes what the result is expected to be,
499: // as T of identity(...) passed for callable(A): B with B known to be int,
500: // but only when that is something the other arguments determine, not the void of callable(A): void
501: $contextReturnType = $contextAcceptor->getReturnType();
502: if (
503: $paramAcceptor->getReturnType()->hasTemplateOrLateResolvableType()
504: && !self::referencesTemplateTypeOf($contextReturnType, $calleeTemplateTypeMap)
505: ) {
506: foreach ($argAcceptor->getReturnType()->inferTemplateTypes($contextReturnType)->getTypes() as $name => $type) {
507: if (isset($ownTypes[$name]) || !$argAcceptor->getTemplateTypeMap()->hasType($name)) {
508: continue;
509: }
510:
511: $ownTypes[$name] = $type;
512: }
513: }
514:
515: foreach ($argAcceptor->getTemplateTypeMap()->getTypes() as $name => $templateType) {
516: if (isset($ownTypes[$name]) || !$templateType instanceof TemplateType) {
517: continue;
518: }
519:
520: $freeName = $templateType->getName();
521: for ($i = 2; isset($usedNames[$freeName]); $i++) {
522: $freeName = $templateType->getName() . $i;
523: }
524: if ($freeName !== $name) {
525: $templateType = TemplateTypeFactory::create(
526: $templateType->getScope(),
527: $freeName,
528: $templateType->getBound(),
529: $templateType->getVariance(),
530: $templateType->getStrategy(),
531: $templateType->getDefault(),
532: );
533: }
534:
535: $usedNames[$freeName] = true;
536: $freeTemplateTypes[$freeName] = $templateType;
537: $ownTypes[$name] = $templateType;
538: }
539:
540: // resolved like a call with these types, so its conditional return type is decided too
541: $ownTypeMap = new TemplateTypeMap($ownTypes);
542: $instantiationArgTypes = $contextParameterTypes;
543: foreach ($argAcceptor->getParameters() as $i => $parameter) {
544: $instantiationArgTypes[$i] ??= TemplateTypeHelper::resolveTemplateTypes($parameter->getType(), $ownTypeMap, TemplateTypeVarianceMap::createEmpty(), TemplateTypeVariance::createContravariant());
545: }
546: $typeMap = self::inferTemplateTypesFromInstantiatedCallable($paramAcceptor, self::resolve($instantiationArgTypes, $argAcceptor));
547: foreach ($typeMap->getTypes() as $name => $type) {
548: $contextTypes[$name] ??= $type;
549: }
550: $typeMaps[$paramName] = $typeMap;
551: }
552:
553: return [$typeMaps, $freeTemplateTypes];
554: }
555:
556: /**
557: * What CallableType::inferTemplateTypes() infers from a callable, without
558: * first instantiating it with the parameter's own types - the instantiated
559: * callable's free templates would take the called function's templates.
560: */
561: private static function inferTemplateTypesFromInstantiatedCallable(ParametersAcceptor $parameterAcceptor, ParametersAcceptor $instantiatedAcceptor): TemplateTypeMap
562: {
563: $instantiatedParameters = $instantiatedAcceptor->getParameters();
564: $lastInstantiatedParameter = array_last($instantiatedParameters);
565: $typeMap = TemplateTypeMap::createEmpty();
566: foreach ($parameterAcceptor->getParameters() as $i => $parameter) {
567: $parameterType = $parameter->getType();
568: if (isset($instantiatedParameters[$i])) {
569: $argType = $instantiatedParameters[$i]->getType();
570: } elseif ($lastInstantiatedParameter !== null && $lastInstantiatedParameter->isVariadic()) {
571: $argType = $lastInstantiatedParameter->getType();
572: } elseif ($parameterType instanceof TemplateType) {
573: $argType = TemplateTypeHelper::resolveToBounds($parameterType);
574: } else {
575: $argType = new NeverType();
576: }
577:
578: $typeMap = $typeMap->union($parameterType->inferTemplateTypes($argType)->swapBounds());
579: }
580:
581: return $typeMap->union($parameterAcceptor->getReturnType()->inferTemplateTypes($instantiatedAcceptor->getReturnType()));
582: }
583:
584: /**
585: * The free templates of generic callables passed to the call (see
586: * instantiateGenericCallables()) that the parameters of a returned
587: * callable mention become its templates: compose(identity(...), identity(...))
588: * is Closure<T>(T): T. The rest resolve to their bounds - no type outside
589: * the callable they came from can bind them.
590: *
591: * @param array<string, TemplateType> $freeTemplateTypes
592: * @return array{ExtendedParametersAcceptor, TemplateTypeMap}
593: */
594: private static function bindFreeTemplateTypes(ExtendedParametersAcceptor $parametersAcceptor, TemplateTypeMap $resolvedTemplateTypeMap, array $freeTemplateTypes): array
595: {
596: $freeTemplateTypeMap = new TemplateTypeMap($freeTemplateTypes);
597: $returnType = $parametersAcceptor->getReturnType();
598: $boundTemplateTypes = [];
599: if (($returnType instanceof ClosureType || $returnType instanceof CallableType) && !$returnType->isCommonCallable()) {
600: foreach ($returnType->getParameters() as $parameter) {
601: $parameterType = TemplateTypeHelper::resolveTemplateTypes($parameter->getType(), $resolvedTemplateTypeMap, TemplateTypeVarianceMap::createEmpty(), TemplateTypeVariance::createContravariant());
602: foreach ($parameterType->getReferencedTemplateTypes(TemplateTypeVariance::createContravariant()) as $reference) {
603: $templateType = $reference->getType();
604: if (!self::isTemplateTypeOf($templateType, $freeTemplateTypeMap)) {
605: continue;
606: }
607:
608: $boundTemplateTypes[$templateType->getName()] = true;
609: }
610: }
611: }
612:
613: // in the order the callables declare them, not the order the parameters mention them
614: $boundTemplateTypes = array_intersect_key($freeTemplateTypes, $boundTemplateTypes);
615: $unboundTemplateTypeMap = new TemplateTypeMap(array_diff_key($freeTemplateTypes, $boundTemplateTypes));
616: if (!$unboundTemplateTypeMap->isEmpty()) {
617: $resolvedTemplateTypeMap = $resolvedTemplateTypeMap->map(static fn (string $name, Type $type): Type => TypeTraverser::map($type, static function (Type $type, callable $traverse) use ($unboundTemplateTypeMap): Type {
618: if (self::isTemplateTypeOf($type, $unboundTemplateTypeMap)) {
619: return TemplateTypeHelper::resolveToBounds($type);
620: }
621:
622: return $traverse($type);
623: }));
624: }
625:
626: if ($boundTemplateTypes === []) {
627: return [$parametersAcceptor, $resolvedTemplateTypeMap];
628: }
629:
630: $phpDocReturnType = $parametersAcceptor->getPhpDocReturnType();
631:
632: return [
633: new ExtendedFunctionVariant(
634: $parametersAcceptor->getTemplateTypeMap(),
635: $parametersAcceptor->getResolvedTemplateTypeMap(),
636: $parametersAcceptor->getParameters(),
637: $parametersAcceptor->isVariadic(),
638: self::withTemplateTypes($returnType, $boundTemplateTypes),
639: self::withTemplateTypes($phpDocReturnType, $boundTemplateTypes),
640: $parametersAcceptor->getNativeReturnType(),
641: $parametersAcceptor->getCallSiteVarianceMap(),
642: ),
643: $resolvedTemplateTypeMap,
644: ];
645: }
646:
647: /**
648: * @param array<string, TemplateType> $templateTypes
649: */
650: private static function withTemplateTypes(Type $type, array $templateTypes): Type
651: {
652: $templateTags = [];
653: foreach ($templateTypes as $templateType) {
654: $templateTags[$templateType->getName()] = new TemplateTag($templateType->getName(), $templateType->getBound(), $templateType->getDefault(), $templateType->getVariance());
655: }
656:
657: if ($type instanceof CallableType && !$type->isCommonCallable()) {
658: return new CallableType(
659: $type->getParameters(),
660: $type->getReturnType(),
661: $type->isVariadic(),
662: new TemplateTypeMap(array_merge($type->getTemplateTypeMap()->getTypes(), $templateTypes)),
663: $type->getResolvedTemplateTypeMap(),
664: array_merge($type->getTemplateTags(), $templateTags),
665: $type->isPure(),
666: $type->getAsserts(),
667: );
668: }
669:
670: if ($type instanceof ClosureType && !$type->isCommonCallable()) {
671: return new ClosureType(
672: $type->getParameters(),
673: $type->getReturnType(),
674: $type->isVariadic(),
675: new TemplateTypeMap(array_merge($type->getTemplateTypeMap()->getTypes(), $templateTypes)),
676: $type->getResolvedTemplateTypeMap(),
677: $type->getCallSiteVarianceMap(),
678: array_merge($type->getTemplateTags(), $templateTags),
679: $type->getThrowPoints(),
680: $type->getImpurePoints(),
681: $type->getInvalidateExpressions(),
682: $type->getUsedVariables(),
683: $type->acceptsNamedArguments(),
684: $type->mustUseReturnValue(),
685: $type->getAsserts(),
686: $type->isStaticClosure(),
687: $type->getByRefUseTypes(),
688: $type->getOrigin(),
689: );
690: }
691:
692: return $type;
693: }
694:
695: private static function referencesTemplateTypeOf(Type $type, TemplateTypeMap $templateTypeMap): bool
696: {
697: if (!$type->hasTemplateOrLateResolvableType()) {
698: return false;
699: }
700:
701: foreach ($type->getReferencedTemplateTypes(TemplateTypeVariance::createCovariant()) as $reference) {
702: if (self::isTemplateTypeOf($reference->getType(), $templateTypeMap)) {
703: return true;
704: }
705: }
706:
707: return false;
708: }
709:
710: private static function isTemplateTypeOf(Type $type, TemplateTypeMap $templateTypeMap): bool
711: {
712: if (!$type instanceof TemplateType) {
713: return false;
714: }
715:
716: $templateType = $templateTypeMap->getType($type->getName());
717:
718: return $templateType instanceof TemplateType && $templateType->getScope()->equals($type->getScope());
719: }
720:
721: /**
722: * The parameters of a callable type like callable(list<B>, list<A>) have no
723: * names, but each takes its own argument, so they are inferred from under
724: * names of their own.
725: *
726: * @param list<ParameterReflection> $parameters
727: * @return list<ParameterReflection>
728: */
729: private static function nameParameters(array $parameters): array
730: {
731: $namedParameters = [];
732: foreach ($parameters as $i => $parameter) {
733: $namedParameters[] = $parameter->getName() !== '' ? $parameter : new NativeParameterReflection(
734: '#' . $i,
735: $parameter->isOptional(),
736: $parameter->getType(),
737: $parameter->passedByReference(),
738: $parameter->isVariadic(),
739: $parameter->getDefaultValue(),
740: );
741: }
742:
743: return $namedParameters;
744: }
745:
746: /**
747: * @param array<string, Type> $namedArgTypes
748: */
749: private static function getArgType(ParameterReflection $param, array $namedArgTypes): ?Type
750: {
751: if (isset($namedArgTypes[$param->getName()])) {
752: return $namedArgTypes[$param->getName()];
753: }
754: if ($param->getDefaultValue() !== null) {
755: return $param->getDefaultValue();
756: }
757: if ($param->isVariadic()) {
758: return new NeverType(true);
759: }
760:
761: return null;
762: }
763:
764: /**
765: * @param list<ParameterReflection> $parameters
766: * @param array<string, Type> $namedArgTypes
767: */
768: private static function createConditionalInference(array $parameters, array $namedArgTypes, TemplateTypeMap $templateTypeMap): ?ConditionalParameterTypeInference
769: {
770: foreach ($parameters as $param) {
771: $type = $param->getType();
772: // a bare template type is the common case and has no conditional type in it
773: if ($type instanceof TemplateType || !ConditionalParameterTypeInference::hasConditionalType($type)) {
774: continue;
775: }
776:
777: $parametersWithArgs = [];
778: foreach ($parameters as $parameter) {
779: if (self::getArgType($parameter, $namedArgTypes) === null) {
780: continue;
781: }
782:
783: $parametersWithArgs[$parameter->getName()] = $parameter;
784: }
785:
786: return new ConditionalParameterTypeInference($parametersWithArgs, $templateTypeMap);
787: }
788:
789: return null;
790: }
791:
792: /**
793: * An argument for a parameter that mentions a template only in invariant positions,
794: * like Inv<int> for Inv<T>, determines the template exactly: other arguments can only
795: * be checked against it, not widen it. So put(Inv<int>, 'a') blames 'a', not the box.
796: *
797: * @param array<string, list<Type>> $pinnedTypes
798: * @return array<string, list<Type>>
799: */
800: private static function collectPinnedTemplateTypes(Type $paramType, TemplateTypeMap $paramTypeMap, array $pinnedTypes): array
801: {
802: if (!$paramType->hasTemplateOrLateResolvableType()) {
803: return $pinnedTypes;
804: }
805:
806: $onlyInvariant = [];
807: foreach ($paramType->getReferencedTemplateTypes(TemplateTypeVariance::createContravariant()) as $reference) {
808: $name = $reference->getType()->getName();
809: $onlyInvariant[$name] = ($onlyInvariant[$name] ?? true) && $reference->getPositionVariance()->invariant();
810: }
811:
812: foreach ($onlyInvariant as $name => $isOnlyInvariant) {
813: if (!$isOnlyInvariant) {
814: continue;
815: }
816:
817: $type = $paramTypeMap->getType($name);
818: if ($type === null || $type instanceof ErrorType || $type instanceof NeverType || $type->hasUnresolvedTemplateArgumentType()) {
819: continue;
820: }
821:
822: $pinnedTypes[$name][] = $type;
823: }
824:
825: return $pinnedTypes;
826: }
827:
828: /**
829: * The pinned type of each template whose pins agree. Pins that disagree, like
830: * both(Inv<int>, Inv<string>), keep the union, so both arguments are reported.
831: *
832: * @param array<string, list<Type>> $pinnedTypes
833: * @return array<string, Type>
834: */
835: private static function resolvePinnedTemplateTypes(array $pinnedTypes): array
836: {
837: $resolved = [];
838: foreach ($pinnedTypes as $name => $types) {
839: foreach ($types as $type) {
840: if (!$type->equals($types[0])) {
841: continue 2;
842: }
843: }
844:
845: $resolved[$name] = $types[0];
846: }
847:
848: return $resolved;
849: }
850:
851: /**
852: * A template that occurs in the return type only in contravariant positions, such as
853: * the T in callable(T): void, makes the return type more precise the larger it is, so it
854: * resolves to its upper bound rather than to the lower bound getTypes() prefers.
855: *
856: * @param array<string, Type> $upperBoundTypes
857: * @return array<string, Type>
858: */
859: private static function resolveContravariantReturnTemplateTypes(Type $returnType, array $upperBoundTypes): array
860: {
861: if ($upperBoundTypes === []) {
862: return [];
863: }
864:
865: $contravariantOnly = [];
866: foreach ($returnType->getReferencedTemplateTypes(TemplateTypeVariance::createCovariant()) as $reference) {
867: $name = $reference->getType()->getName();
868: if (!array_key_exists($name, $upperBoundTypes)) {
869: continue;
870: }
871:
872: $contravariantOnly[$name] = ($contravariantOnly[$name] ?? true) && $reference->getPositionVariance()->contravariant();
873: }
874:
875: $resolved = [];
876: foreach ($contravariantOnly as $name => $isContravariantOnly) {
877: if (!$isContravariantOnly) {
878: continue;
879: }
880:
881: $resolved[$name] = $upperBoundTypes[$name];
882: }
883:
884: return $resolved;
885: }
886:
887: /**
888: * @return TemplateTypeMap|null null when the parameter type is no callable with a type predicate
889: */
890: private static function inferPredicateTemplateTypes(Type $paramType, Type $argType): ?TemplateTypeMap
891: {
892: $typeMap = null;
893: foreach ($paramType instanceof UnionType ? $paramType->getTypes() : [$paramType] as $innerType) {
894: if (!$innerType instanceof CallableParametersAcceptor) {
895: continue;
896: }
897: if ($innerType->getAsserts()->getAll() === []) {
898: continue;
899: }
900:
901: // asked only for parameters with asserts - it reflects the class named by
902: // a callable-like argument
903: $typeMap ??= TemplateTypeMap::createEmpty();
904: if (!$argType->isCallable()->yes()) {
905: return $typeMap;
906: }
907:
908: foreach ($argType->getCallableParametersAcceptors(new OutOfClassScope()) as $receivedAcceptor) {
909: $typeMap = $typeMap->union(CallableAssertionsHelper::inferTemplateTypesOnAsserts($innerType, $receivedAcceptor));
910: }
911: }
912:
913: return $typeMap;
914: }
915:
916: private static function resolvePredicateTemplateTypes(Type $type, TemplateTypeMap $predicateTypeMap): Type
917: {
918: return TemplateTypeHelper::resolveTemplateTypes(
919: $type,
920: $predicateTypeMap,
921: TemplateTypeVarianceMap::createEmpty(),
922: TemplateTypeVariance::createInvariant(),
923: );
924: }
925:
926: }
927: