1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Type;
4:
5: use Closure;
6: use PhpParser\Node\Name\FullyQualified;
7: use PHPStan\Analyser\OutOfClassScope;
8: use PHPStan\Node\InvalidateExprNode;
9: use PHPStan\Php\PhpVersion;
10: use PHPStan\PhpDoc\Tag\TemplateTag;
11: use PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode;
12: use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode;
13: use PHPStan\PhpDocParser\Ast\Type\CallableTypeParameterNode;
14: use PHPStan\PhpDocParser\Ast\Type\FullyQualifiedNameNode;
15: use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
16: use PHPStan\PhpDocParser\Ast\Type\TypeNode;
17: use PHPStan\Reflection\Assertions;
18: use PHPStan\Reflection\Callables\CallableParametersAcceptor;
19: use PHPStan\Reflection\Callables\SimpleImpurePoint;
20: use PHPStan\Reflection\Callables\SimpleThrowPoint;
21: use PHPStan\Reflection\ClassConstantReflection;
22: use PHPStan\Reflection\ClassMemberAccessAnswerer;
23: use PHPStan\Reflection\ClassReflection;
24: use PHPStan\Reflection\ExtendedMethodReflection;
25: use PHPStan\Reflection\ExtendedParameterReflection;
26: use PHPStan\Reflection\ExtendedPropertyReflection;
27: use PHPStan\Reflection\Native\NativeParameterReflection;
28: use PHPStan\Reflection\ParameterReflection;
29: use PHPStan\Reflection\ParametersAcceptor;
30: use PHPStan\Reflection\ParametersAcceptorSelector;
31: use PHPStan\Reflection\PassedByReference;
32: use PHPStan\Reflection\Php\ClosureCallUnresolvedMethodPrototypeReflection;
33: use PHPStan\Reflection\Php\DummyParameter;
34: use PHPStan\Reflection\ReflectionProvider;
35: use PHPStan\Reflection\Type\UnresolvedMethodPrototypeReflection;
36: use PHPStan\Reflection\Type\UnresolvedPropertyPrototypeReflection;
37: use PHPStan\TrinaryLogic;
38: use PHPStan\Turbo\ShadowedByTurboExtension;
39: use PHPStan\Type\Constant\ConstantArrayType;
40: use PHPStan\Type\Constant\ConstantBooleanType;
41: use PHPStan\Type\Constant\ConstantIntegerType;
42: use PHPStan\Type\Enum\EnumCaseObjectType;
43: use PHPStan\Type\Generic\TemplateType;
44: use PHPStan\Type\Generic\TemplateTypeHelper;
45: use PHPStan\Type\Generic\TemplateTypeMap;
46: use PHPStan\Type\Generic\TemplateTypeVariance;
47: use PHPStan\Type\Generic\TemplateTypeVarianceMap;
48: use PHPStan\Type\Generic\UnresolvedTemplateArgumentType;
49: use PHPStan\Type\Traits\NonArrayTypeTrait;
50: use PHPStan\Type\Traits\NonGeneralizableTypeTrait;
51: use PHPStan\Type\Traits\NonIterableTypeTrait;
52: use PHPStan\Type\Traits\NonOffsetAccessibleTypeTrait;
53: use PHPStan\Type\Traits\NonRemoveableTypeTrait;
54: use PHPStan\Type\Traits\OperatorTypeTrait;
55: use PHPStan\Type\Traits\UndecidedComparisonTypeTrait;
56: use function array_key_exists;
57: use function array_map;
58: use function array_merge;
59: use function count;
60: use function in_array;
61:
62: /** @api */
63: #[ShadowedByTurboExtension(implementation: __DIR__ . '/../../turbo-ext/src/ClosureType.cpp')]
64: class ClosureType implements TypeWithClassName, CallableParametersAcceptor
65: {
66:
67: use NonArrayTypeTrait;
68: use NonIterableTypeTrait;
69: use UndecidedComparisonTypeTrait;
70: use NonOffsetAccessibleTypeTrait;
71: use NonRemoveableTypeTrait;
72: use NonGeneralizableTypeTrait;
73: use OperatorTypeTrait;
74:
75: /** @var list<ParameterReflection> */
76: private array $parameters;
77:
78: private Type $returnType;
79:
80: private bool $isCommonCallable;
81:
82: private ObjectType $objectType;
83:
84: private TemplateTypeMap $templateTypeMap;
85:
86: private TemplateTypeMap $resolvedTemplateTypeMap;
87:
88: private TemplateTypeVarianceMap $callSiteVarianceMap;
89:
90: /** @var SimpleImpurePoint[] */
91: private array $impurePoints;
92:
93: private TrinaryLogic $acceptsNamedArguments;
94:
95: private TrinaryLogic $mustUseReturnValue;
96:
97: private Assertions $assertions;
98:
99: private TrinaryLogic $isStatic;
100:
101: /** @var array<int, string> */
102: private array $cachedDescriptions = [];
103:
104: private ?bool $hasUnresolvedTemplateArgumentType = null;
105:
106: /**
107: * @api
108: * @param list<ParameterReflection>|null $parameters
109: * @param array<non-empty-string, TemplateTag> $templateTags
110: * @param SimpleThrowPoint[] $throwPoints
111: * @param ?SimpleImpurePoint[] $impurePoints
112: * @param InvalidateExprNode[] $invalidateExpressions
113: * @param string[] $usedVariables
114: * @param array<string, Type> $byRefUseTypes per by-ref use of a closure whose effects apply where it is invoked, the marker of its site (see ClosureSignatureInference)
115: * @param ClosureOrigin|null $origin the callee of a first-class callable or a partial function application, whose call a call of the closure replays
116: */
117: public function __construct(
118: ?array $parameters = null,
119: ?Type $returnType = null,
120: private bool $variadic = true,
121: ?TemplateTypeMap $templateTypeMap = null,
122: ?TemplateTypeMap $resolvedTemplateTypeMap = null,
123: ?TemplateTypeVarianceMap $callSiteVarianceMap = null,
124: private array $templateTags = [],
125: private array $throwPoints = [],
126: ?array $impurePoints = null,
127: private array $invalidateExpressions = [],
128: private array $usedVariables = [],
129: ?TrinaryLogic $acceptsNamedArguments = null,
130: ?TrinaryLogic $mustUseReturnValue = null,
131: ?Assertions $assertions = null,
132: ?TrinaryLogic $isStatic = null,
133: private array $byRefUseTypes = [],
134: private ?ClosureOrigin $origin = null,
135: )
136: {
137: if ($acceptsNamedArguments === null) {
138: $acceptsNamedArguments = TrinaryLogic::createYes();
139: }
140: $this->acceptsNamedArguments = $acceptsNamedArguments;
141: if ($mustUseReturnValue === null) {
142: $mustUseReturnValue = TrinaryLogic::createMaybe();
143: }
144: $this->mustUseReturnValue = $mustUseReturnValue;
145:
146: $this->parameters = $parameters ?? [];
147: $this->returnType = $returnType ?? new MixedType();
148: $this->isCommonCallable = $parameters === null && $returnType === null;
149: $this->objectType = new ObjectType(Closure::class);
150: $this->templateTypeMap = $templateTypeMap ?? TemplateTypeMap::createEmpty();
151: $this->resolvedTemplateTypeMap = $resolvedTemplateTypeMap ?? TemplateTypeMap::createEmpty();
152: $this->callSiteVarianceMap = $callSiteVarianceMap ?? TemplateTypeVarianceMap::createEmpty();
153: $this->impurePoints = $impurePoints ?? [new SimpleImpurePoint('functionCall', 'call to an unknown Closure', false)];
154: $this->assertions = $assertions ?? Assertions::createEmpty();
155: $this->isStatic = $isStatic ?? TrinaryLogic::createMaybe();
156: }
157:
158: public function getAsserts(): Assertions
159: {
160: return $this->assertions;
161: }
162:
163: /**
164: * @return array<non-empty-string, TemplateTag>
165: */
166: public function getTemplateTags(): array
167: {
168: return $this->templateTags;
169: }
170:
171: public static function createPure(): self
172: {
173: return new self(
174: parameters: null,
175: returnType: null,
176: variadic: true,
177: templateTypeMap: null,
178: resolvedTemplateTypeMap: null,
179: callSiteVarianceMap: null,
180: templateTags: [],
181: throwPoints: [],
182: impurePoints: [],
183: );
184: }
185:
186: public function isPure(): TrinaryLogic
187: {
188: $impurePoints = $this->getImpurePoints();
189: if (count($impurePoints) === 0) {
190: return TrinaryLogic::createYes();
191: }
192:
193: $certainCount = 0;
194: foreach ($impurePoints as $impurePoint) {
195: if (!$impurePoint->isCertain()) {
196: continue;
197: }
198:
199: $certainCount++;
200: }
201:
202: return $certainCount > 0 ? TrinaryLogic::createNo() : TrinaryLogic::createMaybe();
203: }
204:
205: public function getClassName(): string
206: {
207: return $this->objectType->getClassName();
208: }
209:
210: public function getClassReflection(): ?ClassReflection
211: {
212: return $this->objectType->getClassReflection();
213: }
214:
215: public function getAncestorWithClassName(string $className): ?TypeWithClassName
216: {
217: return $this->objectType->getAncestorWithClassName($className);
218: }
219:
220: public function getReferencedClasses(): array
221: {
222: $classes = $this->objectType->getReferencedClasses();
223: foreach ($this->parameters as $parameter) {
224: $classes = array_merge($classes, $parameter->getType()->getReferencedClasses());
225: }
226: foreach ($this->assertions->getAll() as $assertTag) {
227: $classes = array_merge($classes, $assertTag->getType()->getReferencedClasses());
228: }
229:
230: return array_merge($classes, $this->returnType->getReferencedClasses());
231: }
232:
233: public function getObjectClassNames(): array
234: {
235: return $this->objectType->getObjectClassNames();
236: }
237:
238: public function getObjectClassReflections(): array
239: {
240: return $this->objectType->getObjectClassReflections();
241: }
242:
243: public function accepts(Type $type, bool $strictTypes): AcceptsResult
244: {
245: if ($type instanceof CompoundType) {
246: return $type->isAcceptedBy($this, $strictTypes);
247: }
248:
249: if (!$type instanceof ClosureType) {
250: return $this->objectType->accepts($type, $strictTypes);
251: }
252:
253: return $this->isSuperTypeOfInternal($type, true, $strictTypes)->toAcceptsResult();
254: }
255:
256: public function isSuperTypeOf(Type $type): IsSuperTypeOfResult
257: {
258: if ($type instanceof CompoundType) {
259: return $type->isSubTypeOf($this);
260: }
261:
262: return $this->isSuperTypeOfInternal($type, false);
263: }
264:
265: private function isSuperTypeOfInternal(Type $type, bool $treatMixedAsAny, bool $strictTypes = true): IsSuperTypeOfResult
266: {
267: if ($type instanceof self) {
268: $parameterTypes = array_map(static fn ($parameter) => $parameter->getType(), $this->getParameters());
269: $variant = ParametersAcceptorSelector::selectFromTypes($parameterTypes, [$type], false);
270: if (!$variant instanceof CallableParametersAcceptor) {
271: return IsSuperTypeOfResult::createNo([]);
272: }
273: $result = CallableTypeHelper::isParametersAcceptorSuperTypeOf(
274: $this,
275: $variant,
276: $treatMixedAsAny,
277: $strictTypes,
278: );
279: if (!$treatMixedAsAny && $this->origin !== null && !self::hasEqualOrigins($this, $type)) {
280: // a closure created from another callee, or from an unknown one,
281: // is not known to be created from this one
282: return $result->and(IsSuperTypeOfResult::createMaybe());
283: }
284:
285: return $result;
286: }
287:
288: if ($type->getObjectClassNames() === [Closure::class]) {
289: return IsSuperTypeOfResult::createMaybe();
290: }
291:
292: return $this->objectType->isSuperTypeOf($type);
293: }
294:
295: public function equals(Type $type): bool
296: {
297: if (!$type instanceof self) {
298: return false;
299: }
300:
301: return $this->describe(VerbosityLevel::precise()) === $type->describe(VerbosityLevel::precise())
302: && $this->isPure()->equals($type->isPure())
303: && $this->isStatic->equals($type->isStatic)
304: && $this->hasEqualUnresolvedSignature($type)
305: && self::hasEqualOrigins($this, $type);
306: }
307:
308: private static function hasEqualOrigins(self $a, self $b): bool
309: {
310: if ($a->origin === null || $b->origin === null) {
311: return $a->origin === $b->origin;
312: }
313:
314: return $a->origin->equals($b->origin);
315: }
316:
317: /**
318: * An unresolved template argument describes as its delegate, but a closure
319: * whose signature is still being inferred is not the same closure as one
320: * with the delegate types (see ClosureSignatureInference).
321: */
322: private function hasEqualUnresolvedSignature(self $other): bool
323: {
324: $pairs = [[$this->returnType, $other->returnType]];
325: foreach ($this->parameters as $i => $parameter) {
326: if (!isset($other->parameters[$i])) {
327: continue;
328: }
329: $pairs[] = [$parameter->getType(), $other->parameters[$i]->getType()];
330: }
331: foreach ($pairs as [$ours, $theirs]) {
332: if (!$ours instanceof UnresolvedTemplateArgumentType && !$theirs instanceof UnresolvedTemplateArgumentType) {
333: continue;
334: }
335: if (!$ours->equals($theirs)) {
336: return false;
337: }
338: }
339: if (count($this->byRefUseTypes) !== count($other->byRefUseTypes)) {
340: return false;
341: }
342: foreach ($this->byRefUseTypes as $name => $type) {
343: if (!isset($other->byRefUseTypes[$name]) || !$type->equals($other->byRefUseTypes[$name])) {
344: return false;
345: }
346: }
347:
348: return true;
349: }
350:
351: public function describe(VerbosityLevel $level): string
352: {
353: return $this->cachedDescriptions[$level->getLevelValue()] ??= $level->handle(
354: static fn (): string => 'Closure',
355: function (): string {
356: if ($this->isCommonCallable) {
357: $prefix = $this->isStatic->yes() ? 'static-' : '';
358: $name = $this->isPure()->yes() ? 'pure-Closure' : 'Closure';
359: return $prefix . $name;
360: }
361:
362: return $this->describeCallable();
363: },
364: function (): string {
365: $prefix = $this->isStatic->yes() ? 'static-' : '';
366:
367: if ($this->isCommonCallable) {
368: $name = $this->isPure()->yes() ? 'pure-Closure' : 'Closure';
369: return $prefix . $name;
370: }
371:
372: return $prefix . $this->describeCallable();
373: },
374: function (): string {
375: $description = $this->describe(VerbosityLevel::precise());
376: if ($this->origin === null) {
377: return $description;
378: }
379:
380: return $description . ' from ' . $this->origin->describe();
381: },
382: );
383: }
384:
385: private function describeCallable(): string
386: {
387: $assertedParameterNames = [];
388: foreach ($this->assertions->getAll() as $assertTag) {
389: $assertedParameterNames[$assertTag->getParameter()->getParameterName()] = true;
390: }
391: $selfWithoutParameterNames = new self(
392: array_map(static fn (ParameterReflection $p): ParameterReflection => new DummyParameter(
393: array_key_exists('$' . $p->getName(), $assertedParameterNames) ? $p->getName() : '',
394: $p->getType(),
395: optional: $p->isOptional() && !$p->isVariadic(),
396: passedByReference: PassedByReference::createNo(),
397: variadic: $p->isVariadic(),
398: defaultValue: $p->getDefaultValue(),
399: ), $this->parameters),
400: $this->returnType,
401: $this->variadic,
402: $this->templateTypeMap,
403: $this->resolvedTemplateTypeMap,
404: $this->callSiteVarianceMap,
405: $this->templateTags,
406: $this->throwPoints,
407: $this->impurePoints,
408: $this->invalidateExpressions,
409: $this->usedVariables,
410: $this->acceptsNamedArguments,
411: $this->mustUseReturnValue,
412: $this->assertions,
413: $this->isStatic,
414: );
415:
416: return TypeNodeDescriber::describe($selfWithoutParameterNames->toPhpDocNode());
417: }
418:
419: public function isOffsetAccessLegal(): TrinaryLogic
420: {
421: return TrinaryLogic::createNo();
422: }
423:
424: public function isObject(): TrinaryLogic
425: {
426: return $this->objectType->isObject();
427: }
428:
429: public function getClassStringType(): Type
430: {
431: return $this->objectType->getClassStringType();
432: }
433:
434: public function isEnum(): TrinaryLogic
435: {
436: return $this->objectType->isEnum();
437: }
438:
439: public function getTemplateType(string $ancestorClassName, string $templateTypeName): Type
440: {
441: return $this->objectType->getTemplateType($ancestorClassName, $templateTypeName);
442: }
443:
444: public function canAccessProperties(): TrinaryLogic
445: {
446: return $this->objectType->canAccessProperties();
447: }
448:
449: public function hasProperty(string $propertyName): TrinaryLogic
450: {
451: return $this->objectType->hasProperty($propertyName);
452: }
453:
454: public function getProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection
455: {
456: return $this->objectType->getProperty($propertyName, $scope);
457: }
458:
459: public function getUnresolvedPropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection
460: {
461: return $this->objectType->getUnresolvedPropertyPrototype($propertyName, $scope);
462: }
463:
464: public function hasInstanceProperty(string $propertyName): TrinaryLogic
465: {
466: return $this->objectType->hasInstanceProperty($propertyName);
467: }
468:
469: public function getInstanceProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection
470: {
471: return $this->objectType->getInstanceProperty($propertyName, $scope);
472: }
473:
474: public function getUnresolvedInstancePropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection
475: {
476: return $this->objectType->getUnresolvedInstancePropertyPrototype($propertyName, $scope);
477: }
478:
479: public function hasStaticProperty(string $propertyName): TrinaryLogic
480: {
481: return $this->objectType->hasStaticProperty($propertyName);
482: }
483:
484: public function getStaticProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection
485: {
486: return $this->objectType->getStaticProperty($propertyName, $scope);
487: }
488:
489: public function getUnresolvedStaticPropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection
490: {
491: return $this->objectType->getUnresolvedStaticPropertyPrototype($propertyName, $scope);
492: }
493:
494: public function canCallMethods(): TrinaryLogic
495: {
496: return $this->objectType->canCallMethods();
497: }
498:
499: public function hasMethod(string $methodName): TrinaryLogic
500: {
501: return $this->objectType->hasMethod($methodName);
502: }
503:
504: public function getMethod(string $methodName, ClassMemberAccessAnswerer $scope): ExtendedMethodReflection
505: {
506: return $this->getUnresolvedMethodPrototype($methodName, $scope)->getTransformedMethod();
507: }
508:
509: public function getUnresolvedMethodPrototype(string $methodName, ClassMemberAccessAnswerer $scope): UnresolvedMethodPrototypeReflection
510: {
511: if (in_array($methodName, ['call', '__invoke'], true)) {
512: return new ClosureCallUnresolvedMethodPrototypeReflection(
513: $this->objectType->getUnresolvedMethodPrototype($methodName, $scope),
514: $this,
515: $methodName === 'call',
516: );
517: }
518:
519: return $this->objectType->getUnresolvedMethodPrototype($methodName, $scope);
520: }
521:
522: public function canAccessConstants(): TrinaryLogic
523: {
524: return $this->objectType->canAccessConstants();
525: }
526:
527: public function hasConstant(string $constantName): TrinaryLogic
528: {
529: return $this->objectType->hasConstant($constantName);
530: }
531:
532: public function getConstant(string $constantName): ClassConstantReflection
533: {
534: return $this->objectType->getConstant($constantName);
535: }
536:
537: public function getConstantStrings(): array
538: {
539: return [];
540: }
541:
542: public function isIterable(): TrinaryLogic
543: {
544: return TrinaryLogic::createNo();
545: }
546:
547: public function isIterableAtLeastOnce(): TrinaryLogic
548: {
549: return TrinaryLogic::createNo();
550: }
551:
552: public function isCallable(): TrinaryLogic
553: {
554: return TrinaryLogic::createYes();
555: }
556:
557: public function getEnumCases(): array
558: {
559: return [];
560: }
561:
562: public function getEnumCaseObject(): ?EnumCaseObjectType
563: {
564: return null;
565: }
566:
567: public function isCommonCallable(): bool
568: {
569: return $this->isCommonCallable;
570: }
571:
572: public function getCallableParametersAcceptors(ClassMemberAccessAnswerer $scope): array
573: {
574: return [$this];
575: }
576:
577: public function getThrowPoints(): array
578: {
579: return $this->throwPoints;
580: }
581:
582: public function getImpurePoints(): array
583: {
584: return $this->impurePoints;
585: }
586:
587: public function getInvalidateExpressions(): array
588: {
589: return $this->invalidateExpressions;
590: }
591:
592: public function getUsedVariables(): array
593: {
594: return $this->usedVariables;
595: }
596:
597: /** @return array<string, Type> */
598: public function getByRefUseTypes(): array
599: {
600: return $this->byRefUseTypes;
601: }
602:
603: public function getOrigin(): ?ClosureOrigin
604: {
605: return $this->origin;
606: }
607:
608: /**
609: * Memoized: every invocation of a closure asks while its signature is
610: * still being inferred (see ClosureSignatureInference), and a signature
611: * inferred from the invocations is as large as they are many.
612: */
613: public function hasUnresolvedTemplateArgumentType(): bool
614: {
615: if ($this->hasUnresolvedTemplateArgumentType !== null) {
616: return $this->hasUnresolvedTemplateArgumentType;
617: }
618:
619: $contains = false;
620: TypeTraverser::map($this, static function (Type $type, callable $traverse) use (&$contains): Type {
621: if ($type instanceof UnresolvedTemplateArgumentType) {
622: $contains = true;
623: }
624:
625: return $contains ? $type : $traverse($type);
626: });
627:
628: return $this->hasUnresolvedTemplateArgumentType = $contains;
629: }
630:
631: /**
632: * @internal
633: * @deprecated Use hasUnresolvedTemplateArgumentType()
634: */
635: public function containsUnresolvedTemplateArgument(): bool
636: {
637: return $this->hasUnresolvedTemplateArgumentType();
638: }
639:
640: public function acceptsNamedArguments(): TrinaryLogic
641: {
642: return $this->acceptsNamedArguments;
643: }
644:
645: public function mustUseReturnValue(): TrinaryLogic
646: {
647: return $this->mustUseReturnValue;
648: }
649:
650: public function isStaticClosure(): TrinaryLogic
651: {
652: return $this->isStatic;
653: }
654:
655: public function isCloneable(): TrinaryLogic
656: {
657: return TrinaryLogic::createYes();
658: }
659:
660: public function toBoolean(): BooleanType
661: {
662: return new ConstantBooleanType(true);
663: }
664:
665: public function toNumber(): Type
666: {
667: return new ErrorType();
668: }
669:
670: public function toBitwiseNotType(): Type
671: {
672: return new ErrorType();
673: }
674:
675: public function toGetClassResultType(): Type
676: {
677: return $this->getClassStringType();
678: }
679:
680: public function toClassConstantType(ReflectionProvider $reflectionProvider): Type
681: {
682: return $this->objectType->toClassConstantType($reflectionProvider);
683: }
684:
685: public function toObjectTypeForInstanceofCheck(): ClassNameToObjectTypeResult
686: {
687: return new ClassNameToObjectTypeResult($this, true);
688: }
689:
690: public function toObjectTypeForIsACheck(Type $objectOrClassType, bool $allowString, bool $allowSameClass): ClassNameToObjectTypeResult
691: {
692: if ($allowString) {
693: return new ClassNameToObjectTypeResult(
694: new UnionType([new ObjectWithoutClassType(), new ClassStringType()]),
695: false,
696: );
697: }
698:
699: return new ClassNameToObjectTypeResult(new ObjectWithoutClassType(), false);
700: }
701:
702: public function toAbsoluteNumber(): Type
703: {
704: return new ErrorType();
705: }
706:
707: public function toInteger(): Type
708: {
709: return new ErrorType();
710: }
711:
712: public function toFloat(): Type
713: {
714: return new ErrorType();
715: }
716:
717: public function toString(): Type
718: {
719: return new ErrorType();
720: }
721:
722: public function toArray(): Type
723: {
724: return new ConstantArrayType(
725: [new ConstantIntegerType(0)],
726: [$this],
727: [1],
728: isList: TrinaryLogic::createYes(),
729: );
730: }
731:
732: public function toArrayKey(): Type
733: {
734: return new ErrorType();
735: }
736:
737: public function toCoercedArgumentType(bool $strictTypes): Type
738: {
739: return TypeCombinator::union($this, new CallableType());
740: }
741:
742: public function getTemplateTypeMap(): TemplateTypeMap
743: {
744: return $this->templateTypeMap;
745: }
746:
747: public function getResolvedTemplateTypeMap(): TemplateTypeMap
748: {
749: return $this->resolvedTemplateTypeMap;
750: }
751:
752: public function getCallSiteVarianceMap(): TemplateTypeVarianceMap
753: {
754: return $this->callSiteVarianceMap;
755: }
756:
757: /**
758: * @return list<ParameterReflection>
759: */
760: public function getParameters(): array
761: {
762: return $this->parameters;
763: }
764:
765: public function isVariadic(): bool
766: {
767: return $this->variadic;
768: }
769:
770: public function getReturnType(): Type
771: {
772: return $this->returnType;
773: }
774:
775: public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
776: {
777: if ($receivedType instanceof UnionType || $receivedType instanceof IntersectionType) {
778: return $receivedType->inferTemplateTypesOn($this);
779: }
780:
781: if ($receivedType->isCallable()->no() || ! $receivedType instanceof self) {
782: return TemplateTypeMap::createEmpty();
783: }
784:
785: $parametersAcceptors = $receivedType->getCallableParametersAcceptors(new OutOfClassScope());
786:
787: $typeMap = TemplateTypeMap::createEmpty();
788:
789: foreach ($parametersAcceptors as $parametersAcceptor) {
790: $typeMap = $typeMap->union($this->inferTemplateTypesOnParametersAcceptor($parametersAcceptor));
791: }
792:
793: return $typeMap;
794: }
795:
796: private function inferTemplateTypesOnParametersAcceptor(ParametersAcceptor $parametersAcceptor): TemplateTypeMap
797: {
798: $parameterTypes = array_map(static fn ($parameter) => $parameter->getType(), $this->getParameters());
799: $parametersAcceptor = ParametersAcceptorSelector::selectFromTypes($parameterTypes, [$parametersAcceptor], false);
800: $args = $parametersAcceptor->getParameters();
801: $returnType = $parametersAcceptor->getReturnType();
802:
803: $typeMap = TemplateTypeMap::createEmpty();
804: foreach ($this->getParameters() as $i => $param) {
805: $paramType = $param->getType();
806: if (isset($args[$i])) {
807: $argType = $args[$i]->getType();
808: } elseif ($paramType instanceof TemplateType) {
809: $argType = TemplateTypeHelper::resolveToBounds($paramType);
810: } else {
811: $argType = new NeverType();
812: }
813:
814: $typeMap = $typeMap->union($paramType->inferTemplateTypes($argType)->swapBounds());
815: }
816:
817: $typeMap = $typeMap->union(CallableAssertionsHelper::inferTemplateTypesOnAsserts($this, $parametersAcceptor));
818:
819: return $typeMap->union($this->getReturnType()->inferTemplateTypes($returnType));
820: }
821:
822: public function getReferencedTemplateTypes(TemplateTypeVariance $positionVariance): array
823: {
824: $references = $this->getReturnType()->getReferencedTemplateTypes(
825: $positionVariance->compose(TemplateTypeVariance::createCovariant()),
826: );
827:
828: foreach ($this->assertions->getAll() as $assertTag) {
829: foreach ($assertTag->getType()->getReferencedTemplateTypes($positionVariance->compose(TemplateTypeVariance::createCovariant())) as $reference) {
830: $references[] = $reference;
831: }
832: }
833:
834: $paramVariance = $positionVariance->compose(TemplateTypeVariance::createContravariant());
835:
836: foreach ($this->getParameters() as $param) {
837: foreach ($param->getType()->getReferencedTemplateTypes($paramVariance) as $reference) {
838: $references[] = $reference;
839: }
840: }
841:
842: return $references;
843: }
844:
845: public function traverse(callable $cb): Type
846: {
847: if ($this->isCommonCallable) {
848: return $this;
849: }
850:
851: return new self(
852: array_map(static function (ParameterReflection $param) use ($cb): NativeParameterReflection {
853: $defaultValue = $param->getDefaultValue();
854: return new NativeParameterReflection(
855: $param->getName(),
856: $param->isOptional(),
857: $cb($param->getType()),
858: $param->passedByReference(),
859: $param->isVariadic(),
860: $defaultValue !== null ? $cb($defaultValue) : null,
861: );
862: }, $this->getParameters()),
863: $cb($this->getReturnType()),
864: $this->isVariadic(),
865: $this->templateTypeMap,
866: $this->resolvedTemplateTypeMap,
867: $this->callSiteVarianceMap,
868: $this->templateTags,
869: $this->throwPoints,
870: $this->impurePoints,
871: $this->invalidateExpressions,
872: $this->usedVariables,
873: $this->acceptsNamedArguments,
874: $this->mustUseReturnValue,
875: $this->assertions->mapTypes($cb),
876: $this->isStatic,
877: $this->byRefUseTypes,
878: $this->origin?->traverse($cb),
879: );
880: }
881:
882: public function traverseSimultaneously(Type $right, callable $cb): Type
883: {
884: if ($this->isCommonCallable) {
885: return $this;
886: }
887:
888: if (!$right instanceof self) {
889: return $this;
890: }
891:
892: $rightParameters = $right->getParameters();
893: if (count($this->getParameters()) !== count($rightParameters)) {
894: return $this;
895: }
896:
897: $parameters = [];
898: foreach ($this->getParameters() as $i => $leftParam) {
899: $rightParam = $rightParameters[$i];
900: $leftDefaultValue = $leftParam->getDefaultValue();
901: $rightDefaultValue = $rightParam->getDefaultValue();
902: $defaultValue = $leftDefaultValue;
903: if ($leftDefaultValue !== null && $rightDefaultValue !== null) {
904: $defaultValue = $cb($leftDefaultValue, $rightDefaultValue);
905: }
906: $parameters[] = new NativeParameterReflection(
907: $leftParam->getName(),
908: $leftParam->isOptional(),
909: $cb($leftParam->getType(), $rightParam->getType()),
910: $leftParam->passedByReference(),
911: $leftParam->isVariadic(),
912: $defaultValue,
913: );
914: }
915:
916: return new self(
917: $parameters,
918: $cb($this->getReturnType(), $right->getReturnType()),
919: $this->isVariadic(),
920: $this->templateTypeMap,
921: $this->resolvedTemplateTypeMap,
922: $this->callSiteVarianceMap,
923: $this->templateTags,
924: $this->throwPoints,
925: $this->impurePoints,
926: $this->invalidateExpressions,
927: $this->usedVariables,
928: $this->acceptsNamedArguments,
929: $this->mustUseReturnValue,
930: $this->assertions,
931: $this->isStatic,
932: $this->byRefUseTypes,
933: $this->origin,
934: );
935: }
936:
937: public function getKindMask(): int
938: {
939: return TypeKind::OBJECT;
940: }
941:
942: public function isNull(): TrinaryLogic
943: {
944: return TrinaryLogic::createNo();
945: }
946:
947: public function isConstantValue(): TrinaryLogic
948: {
949: return TrinaryLogic::createNo();
950: }
951:
952: public function isConstantScalarValue(): TrinaryLogic
953: {
954: return TrinaryLogic::createNo();
955: }
956:
957: public function getConstantScalarTypes(): array
958: {
959: return [];
960: }
961:
962: public function getConstantScalarValues(): array
963: {
964: return [];
965: }
966:
967: public function isTrue(): TrinaryLogic
968: {
969: return TrinaryLogic::createNo();
970: }
971:
972: public function isFalse(): TrinaryLogic
973: {
974: return TrinaryLogic::createNo();
975: }
976:
977: public function isBoolean(): TrinaryLogic
978: {
979: return TrinaryLogic::createNo();
980: }
981:
982: public function isFloat(): TrinaryLogic
983: {
984: return TrinaryLogic::createNo();
985: }
986:
987: public function isInteger(): TrinaryLogic
988: {
989: return TrinaryLogic::createNo();
990: }
991:
992: public function isString(): TrinaryLogic
993: {
994: return TrinaryLogic::createNo();
995: }
996:
997: public function isNumericString(): TrinaryLogic
998: {
999: return TrinaryLogic::createNo();
1000: }
1001:
1002: public function isDecimalIntegerString(): TrinaryLogic
1003: {
1004: return TrinaryLogic::createNo();
1005: }
1006:
1007: public function isNonEmptyString(): TrinaryLogic
1008: {
1009: return TrinaryLogic::createNo();
1010: }
1011:
1012: public function isNonFalsyString(): TrinaryLogic
1013: {
1014: return TrinaryLogic::createNo();
1015: }
1016:
1017: public function isLiteralString(): TrinaryLogic
1018: {
1019: return TrinaryLogic::createNo();
1020: }
1021:
1022: public function getStringRefinement(): ?int
1023: {
1024: return null;
1025: }
1026:
1027: public function isLowercaseString(): TrinaryLogic
1028: {
1029: return TrinaryLogic::createNo();
1030: }
1031:
1032: public function isClassString(): TrinaryLogic
1033: {
1034: return TrinaryLogic::createNo();
1035: }
1036:
1037: public function isUppercaseString(): TrinaryLogic
1038: {
1039: return TrinaryLogic::createNo();
1040: }
1041:
1042: public function getClassStringObjectType(): Type
1043: {
1044: return new ErrorType();
1045: }
1046:
1047: public function getObjectTypeOrClassStringObjectType(): Type
1048: {
1049: return $this;
1050: }
1051:
1052: public function isVoid(): TrinaryLogic
1053: {
1054: return TrinaryLogic::createNo();
1055: }
1056:
1057: public function isScalar(): TrinaryLogic
1058: {
1059: return TrinaryLogic::createNo();
1060: }
1061:
1062: public function looseCompare(Type $type, PhpVersion $phpVersion): BooleanType
1063: {
1064: return new BooleanType();
1065: }
1066:
1067: public function arithmeticPower(Type $exponent, PhpVersion $phpVersion): Type
1068: {
1069: return new ErrorType();
1070: }
1071:
1072: public function getFiniteTypes(): array
1073: {
1074: return [];
1075: }
1076:
1077: public function toPhpDocNode(): TypeNode
1078: {
1079: if ($this->isCommonCallable) {
1080: $prefix = $this->isStatic->yes() ? 'static-' : '';
1081: if ($prefix === '' && !$this->isPure()->yes()) {
1082: return new FullyQualifiedNameNode(Closure::class);
1083: }
1084:
1085: $name = $this->isPure()->yes() ? 'pure-Closure' : 'Closure';
1086: return new IdentifierTypeNode($prefix . $name);
1087: }
1088:
1089: $parameters = [];
1090: foreach ($this->parameters as $parameter) {
1091: $parameters[] = new CallableTypeParameterNode(
1092: $parameter->getType()->toPhpDocNode(),
1093: !$parameter->passedByReference()->no(),
1094: $parameter->isVariadic(),
1095: $parameter->getName() === '' ? '' : '$' . $parameter->getName(),
1096: $parameter->isOptional(),
1097: );
1098: }
1099:
1100: $templateTags = [];
1101: foreach ($this->templateTags as $templateName => $templateTag) {
1102: $templateTags[] = new TemplateTagValueNode(
1103: $templateName,
1104: $templateTag->getBound()->toPhpDocNode(),
1105: '',
1106: );
1107: }
1108:
1109: $returnTypeNode = CallableAssertionsHelper::toConditionalReturnTypeNode($this->assertions, $this->parameters, $this->returnType)
1110: ?? $this->returnType->toPhpDocNode();
1111:
1112: return new CallableTypeNode(
1113: new FullyQualifiedNameNode(Closure::class),
1114: $parameters,
1115: $returnTypeNode,
1116: $templateTags,
1117: );
1118: }
1119:
1120: public function toNativePhpTypeNode(NativeTypePosition $position)
1121: {
1122: return $position->isClassNameAllowed() ? new FullyQualified('Closure') : null;
1123: }
1124:
1125: public function hasTemplateOrLateResolvableType(): bool
1126: {
1127: foreach ($this->parameters as $parameter) {
1128: if ($parameter->getType()->hasTemplateOrLateResolvableType()) {
1129: return true;
1130: }
1131:
1132: if (!$parameter instanceof ExtendedParameterReflection) {
1133: continue;
1134: }
1135:
1136: if ($parameter->getOutType() !== null && $parameter->getOutType()->hasTemplateOrLateResolvableType()) {
1137: return true;
1138: }
1139: if ($parameter->getClosureThisType() !== null && $parameter->getClosureThisType()->hasTemplateOrLateResolvableType()) {
1140: return true;
1141: }
1142: }
1143:
1144: foreach ($this->assertions->getAll() as $assertTag) {
1145: if ($assertTag->getType()->hasTemplateOrLateResolvableType()) {
1146: return true;
1147: }
1148: }
1149:
1150: return $this->getReturnType()->hasTemplateOrLateResolvableType();
1151: }
1152:
1153: public function toValueSet(): ValueSet
1154: {
1155: return ValueSet::createObjects($this);
1156: }
1157:
1158: public function tryUnion(Type $otherType): ?Type
1159: {
1160: return null;
1161: }
1162:
1163: public function tryIntersect(Type $otherType): ?Type
1164: {
1165: return null;
1166: }
1167:
1168: }
1169: