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