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<non-empty-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<non-empty-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 acceptsNamedArguments(): bool
298: {
299: return true;
300: }
301:
302: public function toNumber(): Type
303: {
304: return new ErrorType();
305: }
306:
307: public function toAbsoluteNumber(): Type
308: {
309: return new ErrorType();
310: }
311:
312: public function toString(): Type
313: {
314: return new ErrorType();
315: }
316:
317: public function toInteger(): Type
318: {
319: return new ErrorType();
320: }
321:
322: public function toFloat(): Type
323: {
324: return new ErrorType();
325: }
326:
327: public function toArray(): Type
328: {
329: return new ArrayType(new MixedType(), new MixedType());
330: }
331:
332: public function toArrayKey(): Type
333: {
334: return new ErrorType();
335: }
336:
337: public function isOffsetAccessLegal(): TrinaryLogic
338: {
339: return TrinaryLogic::createMaybe();
340: }
341:
342: public function getTemplateTypeMap(): TemplateTypeMap
343: {
344: return $this->templateTypeMap;
345: }
346:
347: public function getResolvedTemplateTypeMap(): TemplateTypeMap
348: {
349: return $this->resolvedTemplateTypeMap;
350: }
351:
352: public function getCallSiteVarianceMap(): TemplateTypeVarianceMap
353: {
354: return TemplateTypeVarianceMap::createEmpty();
355: }
356:
357: /**
358: * @return array<int, ParameterReflection>
359: */
360: public function getParameters(): array
361: {
362: return $this->parameters;
363: }
364:
365: public function isVariadic(): bool
366: {
367: return $this->variadic;
368: }
369:
370: public function getReturnType(): Type
371: {
372: return $this->returnType;
373: }
374:
375: public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
376: {
377: if ($receivedType instanceof UnionType || $receivedType instanceof IntersectionType) {
378: return $receivedType->inferTemplateTypesOn($this);
379: }
380:
381: if (! $receivedType->isCallable()->yes()) {
382: return TemplateTypeMap::createEmpty();
383: }
384:
385: $parametersAcceptors = $receivedType->getCallableParametersAcceptors(new OutOfClassScope());
386:
387: $typeMap = TemplateTypeMap::createEmpty();
388:
389: foreach ($parametersAcceptors as $parametersAcceptor) {
390: $typeMap = $typeMap->union($this->inferTemplateTypesOnParametersAcceptor($parametersAcceptor));
391: }
392:
393: return $typeMap;
394: }
395:
396: private function inferTemplateTypesOnParametersAcceptor(ParametersAcceptor $parametersAcceptor): TemplateTypeMap
397: {
398: $typeMap = TemplateTypeMap::createEmpty();
399: $args = $parametersAcceptor->getParameters();
400: $returnType = $parametersAcceptor->getReturnType();
401:
402: foreach ($this->getParameters() as $i => $param) {
403: $paramType = $param->getType();
404: if (isset($args[$i])) {
405: $argType = $args[$i]->getType();
406: } elseif ($paramType instanceof TemplateType) {
407: $argType = TemplateTypeHelper::resolveToBounds($paramType);
408: } else {
409: $argType = new NeverType();
410: }
411:
412: $typeMap = $typeMap->union($paramType->inferTemplateTypes($argType)->convertToLowerBoundTypes());
413: }
414:
415: return $typeMap->union($this->getReturnType()->inferTemplateTypes($returnType));
416: }
417:
418: public function getReferencedTemplateTypes(TemplateTypeVariance $positionVariance): array
419: {
420: $references = $this->getReturnType()->getReferencedTemplateTypes(
421: $positionVariance->compose(TemplateTypeVariance::createCovariant()),
422: );
423:
424: $paramVariance = $positionVariance->compose(TemplateTypeVariance::createContravariant());
425:
426: foreach ($this->getParameters() as $param) {
427: foreach ($param->getType()->getReferencedTemplateTypes($paramVariance) as $reference) {
428: $references[] = $reference;
429: }
430: }
431:
432: return $references;
433: }
434:
435: public function traverse(callable $cb): Type
436: {
437: if ($this->isCommonCallable) {
438: return $this;
439: }
440:
441: $parameters = array_map(static function (ParameterReflection $param) use ($cb): NativeParameterReflection {
442: $defaultValue = $param->getDefaultValue();
443: return new NativeParameterReflection(
444: $param->getName(),
445: $param->isOptional(),
446: $cb($param->getType()),
447: $param->passedByReference(),
448: $param->isVariadic(),
449: $defaultValue !== null ? $cb($defaultValue) : null,
450: );
451: }, $this->getParameters());
452:
453: return new self(
454: $parameters,
455: $cb($this->getReturnType()),
456: $this->isVariadic(),
457: $this->templateTypeMap,
458: $this->resolvedTemplateTypeMap,
459: $this->templateTags,
460: $this->isPure,
461: );
462: }
463:
464: public function traverseSimultaneously(Type $right, callable $cb): Type
465: {
466: if ($this->isCommonCallable) {
467: return $this;
468: }
469:
470: if (!$right->isCallable()->yes()) {
471: return $this;
472: }
473:
474: $rightAcceptors = $right->getCallableParametersAcceptors(new OutOfClassScope());
475: if (count($rightAcceptors) !== 1) {
476: return $this;
477: }
478:
479: $rightParameters = $rightAcceptors[0]->getParameters();
480: if (count($this->getParameters()) !== count($rightParameters)) {
481: return $this;
482: }
483:
484: $parameters = [];
485: foreach ($this->getParameters() as $i => $leftParam) {
486: $rightParam = $rightParameters[$i];
487: $leftDefaultValue = $leftParam->getDefaultValue();
488: $rightDefaultValue = $rightParam->getDefaultValue();
489: $defaultValue = $leftDefaultValue;
490: if ($leftDefaultValue !== null && $rightDefaultValue !== null) {
491: $defaultValue = $cb($leftDefaultValue, $rightDefaultValue);
492: }
493: $parameters[] = new NativeParameterReflection(
494: $leftParam->getName(),
495: $leftParam->isOptional(),
496: $cb($leftParam->getType(), $rightParam->getType()),
497: $leftParam->passedByReference(),
498: $leftParam->isVariadic(),
499: $defaultValue,
500: );
501: }
502:
503: return new self(
504: $parameters,
505: $cb($this->getReturnType(), $rightAcceptors[0]->getReturnType()),
506: $this->isVariadic(),
507: $this->templateTypeMap,
508: $this->resolvedTemplateTypeMap,
509: $this->templateTags,
510: $this->isPure,
511: );
512: }
513:
514: public function isOversizedArray(): TrinaryLogic
515: {
516: return TrinaryLogic::createNo();
517: }
518:
519: public function isNull(): TrinaryLogic
520: {
521: return TrinaryLogic::createNo();
522: }
523:
524: public function isConstantValue(): TrinaryLogic
525: {
526: return TrinaryLogic::createNo();
527: }
528:
529: public function isConstantScalarValue(): TrinaryLogic
530: {
531: return TrinaryLogic::createNo();
532: }
533:
534: public function getConstantScalarTypes(): array
535: {
536: return [];
537: }
538:
539: public function getConstantScalarValues(): array
540: {
541: return [];
542: }
543:
544: public function isTrue(): TrinaryLogic
545: {
546: return TrinaryLogic::createNo();
547: }
548:
549: public function isFalse(): TrinaryLogic
550: {
551: return TrinaryLogic::createNo();
552: }
553:
554: public function isBoolean(): TrinaryLogic
555: {
556: return TrinaryLogic::createNo();
557: }
558:
559: public function isFloat(): TrinaryLogic
560: {
561: return TrinaryLogic::createNo();
562: }
563:
564: public function isInteger(): TrinaryLogic
565: {
566: return TrinaryLogic::createNo();
567: }
568:
569: public function isString(): TrinaryLogic
570: {
571: return TrinaryLogic::createMaybe();
572: }
573:
574: public function isNumericString(): TrinaryLogic
575: {
576: return TrinaryLogic::createNo();
577: }
578:
579: public function isNonEmptyString(): TrinaryLogic
580: {
581: return TrinaryLogic::createMaybe();
582: }
583:
584: public function isNonFalsyString(): TrinaryLogic
585: {
586: return TrinaryLogic::createMaybe();
587: }
588:
589: public function isLiteralString(): TrinaryLogic
590: {
591: return TrinaryLogic::createMaybe();
592: }
593:
594: public function isClassStringType(): TrinaryLogic
595: {
596: return TrinaryLogic::createMaybe();
597: }
598:
599: public function getClassStringObjectType(): Type
600: {
601: return new ObjectWithoutClassType();
602: }
603:
604: public function getObjectTypeOrClassStringObjectType(): Type
605: {
606: return new ObjectWithoutClassType();
607: }
608:
609: public function isVoid(): TrinaryLogic
610: {
611: return TrinaryLogic::createNo();
612: }
613:
614: public function isScalar(): TrinaryLogic
615: {
616: return TrinaryLogic::createMaybe();
617: }
618:
619: public function looseCompare(Type $type, PhpVersion $phpVersion): BooleanType
620: {
621: return new BooleanType();
622: }
623:
624: public function getEnumCases(): array
625: {
626: return [];
627: }
628:
629: public function isCommonCallable(): bool
630: {
631: return $this->isCommonCallable;
632: }
633:
634: public function exponentiate(Type $exponent): Type
635: {
636: return new ErrorType();
637: }
638:
639: public function getFiniteTypes(): array
640: {
641: return [];
642: }
643:
644: public function toPhpDocNode(): TypeNode
645: {
646: if ($this->isCommonCallable) {
647: return new IdentifierTypeNode($this->isPure()->yes() ? 'pure-callable' : 'callable');
648: }
649:
650: $parameters = [];
651: foreach ($this->parameters as $parameter) {
652: $parameters[] = new CallableTypeParameterNode(
653: $parameter->getType()->toPhpDocNode(),
654: !$parameter->passedByReference()->no(),
655: $parameter->isVariadic(),
656: $parameter->getName() === '' ? '' : '$' . $parameter->getName(),
657: $parameter->isOptional(),
658: );
659: }
660:
661: $templateTags = [];
662: foreach ($this->templateTags as $templateName => $templateTag) {
663: $templateTags[] = new TemplateTagValueNode(
664: $templateName,
665: $templateTag->getBound()->toPhpDocNode(),
666: '',
667: );
668: }
669:
670: return new CallableTypeNode(
671: new IdentifierTypeNode($this->isPure->yes() ? 'pure-callable' : 'callable'),
672: $parameters,
673: $this->returnType->toPhpDocNode(),
674: $templateTags,
675: );
676: }
677:
678: /**
679: * @param mixed[] $properties
680: */
681: public static function __set_state(array $properties): Type
682: {
683: return new self(
684: (bool) $properties['isCommonCallable'] ? null : $properties['parameters'],
685: (bool) $properties['isCommonCallable'] ? null : $properties['returnType'],
686: $properties['variadic'],
687: $properties['templateTypeMap'],
688: $properties['resolvedTemplateTypeMap'],
689: $properties['templateTags'],
690: $properties['isPure'],
691: );
692: }
693:
694: }
695: