1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Type;
4:
5: use PHPStan\Analyser\OutOfClassScope;
6: use PHPStan\Php\PhpVersion;
7: use PHPStan\PhpDoc\Tag\TemplateTag;
8: use PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode;
9: use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode;
10: use PHPStan\PhpDocParser\Ast\Type\CallableTypeParameterNode;
11: use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
12: use PHPStan\PhpDocParser\Ast\Type\TypeNode;
13: use PHPStan\PhpDocParser\Printer\Printer;
14: use PHPStan\Reflection\Callables\CallableParametersAcceptor;
15: use PHPStan\Reflection\Callables\SimpleImpurePoint;
16: use PHPStan\Reflection\Callables\SimpleThrowPoint;
17: use PHPStan\Reflection\ClassMemberAccessAnswerer;
18: use PHPStan\Reflection\Native\NativeParameterReflection;
19: use PHPStan\Reflection\ParameterReflection;
20: use PHPStan\Reflection\ParametersAcceptor;
21: use PHPStan\Reflection\PassedByReference;
22: use PHPStan\Reflection\Php\DummyParameter;
23: use PHPStan\ShouldNotHappenException;
24: use PHPStan\TrinaryLogic;
25: use PHPStan\Type\Generic\TemplateType;
26: use PHPStan\Type\Generic\TemplateTypeHelper;
27: use PHPStan\Type\Generic\TemplateTypeMap;
28: use PHPStan\Type\Generic\TemplateTypeVariance;
29: use PHPStan\Type\Generic\TemplateTypeVarianceMap;
30: use PHPStan\Type\Traits\MaybeArrayTypeTrait;
31: use PHPStan\Type\Traits\MaybeIterableTypeTrait;
32: use PHPStan\Type\Traits\MaybeObjectTypeTrait;
33: use PHPStan\Type\Traits\MaybeOffsetAccessibleTypeTrait;
34: use PHPStan\Type\Traits\NonGeneralizableTypeTrait;
35: use PHPStan\Type\Traits\NonRemoveableTypeTrait;
36: use PHPStan\Type\Traits\TruthyBooleanTypeTrait;
37: use PHPStan\Type\Traits\UndecidedComparisonCompoundTypeTrait;
38: use function array_map;
39: use function array_merge;
40: use function count;
41:
42: /** @api */
43: class CallableType implements CompoundType, CallableParametersAcceptor
44: {
45:
46: use MaybeArrayTypeTrait;
47: use MaybeIterableTypeTrait;
48: use MaybeObjectTypeTrait;
49: use MaybeOffsetAccessibleTypeTrait;
50: use TruthyBooleanTypeTrait;
51: use UndecidedComparisonCompoundTypeTrait;
52: use NonRemoveableTypeTrait;
53: use NonGeneralizableTypeTrait;
54:
55: /** @var array<int, ParameterReflection> */
56: private array $parameters;
57:
58: private Type $returnType;
59:
60: private bool $isCommonCallable;
61:
62: private TemplateTypeMap $templateTypeMap;
63:
64: private TemplateTypeMap $resolvedTemplateTypeMap;
65:
66: private TrinaryLogic $isPure;
67:
68: /**
69: * @api
70: * @param array<int, ParameterReflection>|null $parameters
71: * @param array<string, TemplateTag> $templateTags
72: */
73: public function __construct(
74: ?array $parameters = null,
75: ?Type $returnType = null,
76: private bool $variadic = true,
77: ?TemplateTypeMap $templateTypeMap = null,
78: ?TemplateTypeMap $resolvedTemplateTypeMap = null,
79: private array $templateTags = [],
80: ?TrinaryLogic $isPure = null,
81: )
82: {
83: $this->parameters = $parameters ?? [];
84: $this->returnType = $returnType ?? new MixedType();
85: $this->isCommonCallable = $parameters === null && $returnType === null;
86: $this->templateTypeMap = $templateTypeMap ?? TemplateTypeMap::createEmpty();
87: $this->resolvedTemplateTypeMap = $resolvedTemplateTypeMap ?? TemplateTypeMap::createEmpty();
88: $this->isPure = $isPure ?? TrinaryLogic::createMaybe();
89: }
90:
91: /**
92: * @return array<string, TemplateTag>
93: */
94: public function getTemplateTags(): array
95: {
96: return $this->templateTags;
97: }
98:
99: public function isPure(): TrinaryLogic
100: {
101: return $this->isPure;
102: }
103:
104: /**
105: * @return string[]
106: */
107: public function getReferencedClasses(): array
108: {
109: $classes = [];
110: foreach ($this->parameters as $parameter) {
111: $classes = array_merge($classes, $parameter->getType()->getReferencedClasses());
112: }
113:
114: return array_merge($classes, $this->returnType->getReferencedClasses());
115: }
116:
117: public function getObjectClassNames(): array
118: {
119: return [];
120: }
121:
122: public function getObjectClassReflections(): array
123: {
124: return [];
125: }
126:
127: public function getConstantStrings(): array
128: {
129: return [];
130: }
131:
132: public function accepts(Type $type, bool $strictTypes): TrinaryLogic
133: {
134: return $this->acceptsWithReason($type, $strictTypes)->result;
135: }
136:
137: public function acceptsWithReason(Type $type, bool $strictTypes): AcceptsResult
138: {
139: if ($type instanceof CompoundType && !$type instanceof self) {
140: return $type->isAcceptedWithReasonBy($this, $strictTypes);
141: }
142:
143: return $this->isSuperTypeOfInternal($type, true);
144: }
145:
146: public function isSuperTypeOf(Type $type): TrinaryLogic
147: {
148: if ($type instanceof CompoundType && !$type instanceof self) {
149: return $type->isSubTypeOf($this);
150: }
151:
152: return $this->isSuperTypeOfInternal($type, false)->result;
153: }
154:
155: private function isSuperTypeOfInternal(Type $type, bool $treatMixedAsAny): AcceptsResult
156: {
157: $isCallable = new AcceptsResult($type->isCallable(), []);
158: if ($isCallable->no()) {
159: return $isCallable;
160: }
161:
162: static $scope;
163: if ($scope === null) {
164: $scope = new OutOfClassScope();
165: }
166:
167: if ($this->isCommonCallable) {
168: if ($this->isPure()->yes()) {
169: $typePure = TrinaryLogic::createYes();
170: foreach ($type->getCallableParametersAcceptors($scope) as $variant) {
171: $typePure = $typePure->and($variant->isPure());
172: }
173:
174: return $isCallable->and(new AcceptsResult($typePure, []));
175: }
176:
177: return $isCallable;
178: }
179:
180: $variantsResult = null;
181: foreach ($type->getCallableParametersAcceptors($scope) as $variant) {
182: $isSuperType = CallableTypeHelper::isParametersAcceptorSuperTypeOf($this, $variant, $treatMixedAsAny);
183: if ($variantsResult === null) {
184: $variantsResult = $isSuperType;
185: } else {
186: $variantsResult = $variantsResult->or($isSuperType);
187: }
188: }
189:
190: if ($variantsResult === null) {
191: throw new ShouldNotHappenException();
192: }
193:
194: return $isCallable->and($variantsResult);
195: }
196:
197: public function isSubTypeOf(Type $otherType): TrinaryLogic
198: {
199: if ($otherType instanceof IntersectionType || $otherType instanceof UnionType) {
200: return $otherType->isSuperTypeOf($this);
201: }
202:
203: return $otherType->isCallable()
204: ->and($otherType instanceof self ? TrinaryLogic::createYes() : TrinaryLogic::createMaybe());
205: }
206:
207: public function isAcceptedBy(Type $acceptingType, bool $strictTypes): TrinaryLogic
208: {
209: return $this->isAcceptedWithReasonBy($acceptingType, $strictTypes)->result;
210: }
211:
212: public function isAcceptedWithReasonBy(Type $acceptingType, bool $strictTypes): AcceptsResult
213: {
214: return new AcceptsResult($this->isSubTypeOf($acceptingType), []);
215: }
216:
217: public function equals(Type $type): bool
218: {
219: if (!$type instanceof self) {
220: return false;
221: }
222:
223: return $this->describe(VerbosityLevel::precise()) === $type->describe(VerbosityLevel::precise());
224: }
225:
226: public function describe(VerbosityLevel $level): string
227: {
228: return $level->handle(
229: static fn (): string => 'callable',
230: function (): string {
231: $printer = new Printer();
232: $selfWithoutParameterNames = new self(
233: array_map(static fn (ParameterReflection $p): ParameterReflection => new DummyParameter(
234: '',
235: $p->getType(),
236: $p->isOptional() && !$p->isVariadic(),
237: PassedByReference::createNo(),
238: $p->isVariadic(),
239: $p->getDefaultValue(),
240: ), $this->parameters),
241: $this->returnType,
242: $this->variadic,
243: $this->templateTypeMap,
244: $this->resolvedTemplateTypeMap,
245: $this->templateTags,
246: $this->isPure,
247: );
248:
249: return $printer->print($selfWithoutParameterNames->toPhpDocNode());
250: },
251: );
252: }
253:
254: public function isCallable(): TrinaryLogic
255: {
256: return TrinaryLogic::createYes();
257: }
258:
259: public function getCallableParametersAcceptors(ClassMemberAccessAnswerer $scope): array
260: {
261: return [$this];
262: }
263:
264: public function getThrowPoints(): array
265: {
266: return [
267: SimpleThrowPoint::createImplicit(),
268: ];
269: }
270:
271: public function getImpurePoints(): array
272: {
273: $pure = $this->isPure();
274: if ($pure->yes()) {
275: return [];
276: }
277:
278: return [
279: new SimpleImpurePoint(
280: 'functionCall',
281: 'call to a callable',
282: $pure->no(),
283: ),
284: ];
285: }
286:
287: public function getInvalidateExpressions(): array
288: {
289: return [];
290: }
291:
292: public function getUsedVariables(): array
293: {
294: return [];
295: }
296:
297: public function toNumber(): Type
298: {
299: return new ErrorType();
300: }
301:
302: public function toString(): Type
303: {
304: return new ErrorType();
305: }
306:
307: public function toInteger(): Type
308: {
309: return new ErrorType();
310: }
311:
312: public function toFloat(): Type
313: {
314: return new ErrorType();
315: }
316:
317: public function toArray(): Type
318: {
319: return new ArrayType(new MixedType(), new MixedType());
320: }
321:
322: public function toArrayKey(): Type
323: {
324: return new ErrorType();
325: }
326:
327: public function getTemplateTypeMap(): TemplateTypeMap
328: {
329: return $this->templateTypeMap;
330: }
331:
332: public function getResolvedTemplateTypeMap(): TemplateTypeMap
333: {
334: return $this->resolvedTemplateTypeMap;
335: }
336:
337: public function getCallSiteVarianceMap(): TemplateTypeVarianceMap
338: {
339: return TemplateTypeVarianceMap::createEmpty();
340: }
341:
342: /**
343: * @return array<int, ParameterReflection>
344: */
345: public function getParameters(): array
346: {
347: return $this->parameters;
348: }
349:
350: public function isVariadic(): bool
351: {
352: return $this->variadic;
353: }
354:
355: public function getReturnType(): Type
356: {
357: return $this->returnType;
358: }
359:
360: public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
361: {
362: if ($receivedType instanceof UnionType || $receivedType instanceof IntersectionType) {
363: return $receivedType->inferTemplateTypesOn($this);
364: }
365:
366: if (! $receivedType->isCallable()->yes()) {
367: return TemplateTypeMap::createEmpty();
368: }
369:
370: $parametersAcceptors = $receivedType->getCallableParametersAcceptors(new OutOfClassScope());
371:
372: $typeMap = TemplateTypeMap::createEmpty();
373:
374: foreach ($parametersAcceptors as $parametersAcceptor) {
375: $typeMap = $typeMap->union($this->inferTemplateTypesOnParametersAcceptor($parametersAcceptor));
376: }
377:
378: return $typeMap;
379: }
380:
381: private function inferTemplateTypesOnParametersAcceptor(ParametersAcceptor $parametersAcceptor): TemplateTypeMap
382: {
383: $typeMap = TemplateTypeMap::createEmpty();
384: $args = $parametersAcceptor->getParameters();
385: $returnType = $parametersAcceptor->getReturnType();
386:
387: foreach ($this->getParameters() as $i => $param) {
388: $paramType = $param->getType();
389: if (isset($args[$i])) {
390: $argType = $args[$i]->getType();
391: } elseif ($paramType instanceof TemplateType) {
392: $argType = TemplateTypeHelper::resolveToBounds($paramType);
393: } else {
394: $argType = new NeverType();
395: }
396:
397: $typeMap = $typeMap->union($paramType->inferTemplateTypes($argType)->convertToLowerBoundTypes());
398: }
399:
400: return $typeMap->union($this->getReturnType()->inferTemplateTypes($returnType));
401: }
402:
403: public function getReferencedTemplateTypes(TemplateTypeVariance $positionVariance): array
404: {
405: $references = $this->getReturnType()->getReferencedTemplateTypes(
406: $positionVariance->compose(TemplateTypeVariance::createCovariant()),
407: );
408:
409: $paramVariance = $positionVariance->compose(TemplateTypeVariance::createContravariant());
410:
411: foreach ($this->getParameters() as $param) {
412: foreach ($param->getType()->getReferencedTemplateTypes($paramVariance) as $reference) {
413: $references[] = $reference;
414: }
415: }
416:
417: return $references;
418: }
419:
420: public function traverse(callable $cb): Type
421: {
422: if ($this->isCommonCallable) {
423: return $this;
424: }
425:
426: $parameters = array_map(static function (ParameterReflection $param) use ($cb): NativeParameterReflection {
427: $defaultValue = $param->getDefaultValue();
428: return new NativeParameterReflection(
429: $param->getName(),
430: $param->isOptional(),
431: $cb($param->getType()),
432: $param->passedByReference(),
433: $param->isVariadic(),
434: $defaultValue !== null ? $cb($defaultValue) : null,
435: );
436: }, $this->getParameters());
437:
438: return new self(
439: $parameters,
440: $cb($this->getReturnType()),
441: $this->isVariadic(),
442: $this->templateTypeMap,
443: $this->resolvedTemplateTypeMap,
444: $this->templateTags,
445: $this->isPure,
446: );
447: }
448:
449: public function traverseSimultaneously(Type $right, callable $cb): Type
450: {
451: if ($this->isCommonCallable) {
452: return $this;
453: }
454:
455: if (!$right->isCallable()->yes()) {
456: return $this;
457: }
458:
459: $rightAcceptors = $right->getCallableParametersAcceptors(new OutOfClassScope());
460: if (count($rightAcceptors) !== 1) {
461: return $this;
462: }
463:
464: $rightParameters = $rightAcceptors[0]->getParameters();
465: if (count($this->getParameters()) !== count($rightParameters)) {
466: return $this;
467: }
468:
469: $parameters = [];
470: foreach ($this->getParameters() as $i => $leftParam) {
471: $rightParam = $rightParameters[$i];
472: $leftDefaultValue = $leftParam->getDefaultValue();
473: $rightDefaultValue = $rightParam->getDefaultValue();
474: $defaultValue = $leftDefaultValue;
475: if ($leftDefaultValue !== null && $rightDefaultValue !== null) {
476: $defaultValue = $cb($leftDefaultValue, $rightDefaultValue);
477: }
478: $parameters[] = new NativeParameterReflection(
479: $leftParam->getName(),
480: $leftParam->isOptional(),
481: $cb($leftParam->getType(), $rightParam->getType()),
482: $leftParam->passedByReference(),
483: $leftParam->isVariadic(),
484: $defaultValue,
485: );
486: }
487:
488: return new self(
489: $parameters,
490: $cb($this->getReturnType(), $rightAcceptors[0]->getReturnType()),
491: $this->isVariadic(),
492: $this->templateTypeMap,
493: $this->resolvedTemplateTypeMap,
494: $this->templateTags,
495: $this->isPure,
496: );
497: }
498:
499: public function isOversizedArray(): TrinaryLogic
500: {
501: return TrinaryLogic::createNo();
502: }
503:
504: public function isNull(): TrinaryLogic
505: {
506: return TrinaryLogic::createNo();
507: }
508:
509: public function isConstantValue(): TrinaryLogic
510: {
511: return TrinaryLogic::createNo();
512: }
513:
514: public function isConstantScalarValue(): TrinaryLogic
515: {
516: return TrinaryLogic::createNo();
517: }
518:
519: public function getConstantScalarTypes(): array
520: {
521: return [];
522: }
523:
524: public function getConstantScalarValues(): array
525: {
526: return [];
527: }
528:
529: public function isTrue(): TrinaryLogic
530: {
531: return TrinaryLogic::createNo();
532: }
533:
534: public function isFalse(): TrinaryLogic
535: {
536: return TrinaryLogic::createNo();
537: }
538:
539: public function isBoolean(): TrinaryLogic
540: {
541: return TrinaryLogic::createNo();
542: }
543:
544: public function isFloat(): TrinaryLogic
545: {
546: return TrinaryLogic::createNo();
547: }
548:
549: public function isInteger(): TrinaryLogic
550: {
551: return TrinaryLogic::createNo();
552: }
553:
554: public function isString(): TrinaryLogic
555: {
556: return TrinaryLogic::createMaybe();
557: }
558:
559: public function isNumericString(): TrinaryLogic
560: {
561: return TrinaryLogic::createNo();
562: }
563:
564: public function isNonEmptyString(): TrinaryLogic
565: {
566: return TrinaryLogic::createMaybe();
567: }
568:
569: public function isNonFalsyString(): TrinaryLogic
570: {
571: return TrinaryLogic::createMaybe();
572: }
573:
574: public function isLiteralString(): TrinaryLogic
575: {
576: return TrinaryLogic::createMaybe();
577: }
578:
579: public function isClassStringType(): TrinaryLogic
580: {
581: return TrinaryLogic::createMaybe();
582: }
583:
584: public function getClassStringObjectType(): Type
585: {
586: return new ObjectWithoutClassType();
587: }
588:
589: public function getObjectTypeOrClassStringObjectType(): Type
590: {
591: return new ObjectWithoutClassType();
592: }
593:
594: public function isVoid(): TrinaryLogic
595: {
596: return TrinaryLogic::createNo();
597: }
598:
599: public function isScalar(): TrinaryLogic
600: {
601: return TrinaryLogic::createMaybe();
602: }
603:
604: public function looseCompare(Type $type, PhpVersion $phpVersion): BooleanType
605: {
606: return new BooleanType();
607: }
608:
609: public function getEnumCases(): array
610: {
611: return [];
612: }
613:
614: public function isCommonCallable(): bool
615: {
616: return $this->isCommonCallable;
617: }
618:
619: public function exponentiate(Type $exponent): Type
620: {
621: return new ErrorType();
622: }
623:
624: public function getFiniteTypes(): array
625: {
626: return [];
627: }
628:
629: public function toPhpDocNode(): TypeNode
630: {
631: if ($this->isCommonCallable) {
632: return new IdentifierTypeNode($this->isPure()->yes() ? 'pure-callable' : 'callable');
633: }
634:
635: $parameters = [];
636: foreach ($this->parameters as $parameter) {
637: $parameters[] = new CallableTypeParameterNode(
638: $parameter->getType()->toPhpDocNode(),
639: !$parameter->passedByReference()->no(),
640: $parameter->isVariadic(),
641: $parameter->getName() === '' ? '' : '$' . $parameter->getName(),
642: $parameter->isOptional(),
643: );
644: }
645:
646: $templateTags = [];
647: foreach ($this->templateTags as $templateName => $templateTag) {
648: $templateTags[] = new TemplateTagValueNode(
649: $templateName,
650: $templateTag->getBound()->toPhpDocNode(),
651: '',
652: );
653: }
654:
655: return new CallableTypeNode(
656: new IdentifierTypeNode($this->isPure->yes() ? 'pure-callable' : 'callable'),
657: $parameters,
658: $this->returnType->toPhpDocNode(),
659: $templateTags,
660: );
661: }
662:
663: /**
664: * @param mixed[] $properties
665: */
666: public static function __set_state(array $properties): Type
667: {
668: return new self(
669: (bool) $properties['isCommonCallable'] ? null : $properties['parameters'],
670: (bool) $properties['isCommonCallable'] ? null : $properties['returnType'],
671: $properties['variadic'],
672: $properties['templateTypeMap'],
673: $properties['resolvedTemplateTypeMap'],
674: $properties['templateTags'],
675: $properties['isPure'],
676: );
677: }
678:
679: }
680: