1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Type;
4:
5: use Closure;
6: use PhpParser\Comment\Doc;
7: use PhpParser\Node;
8: use PHPStan\Analyser\NameScope;
9: use PHPStan\BetterReflection\Util\GetLastDocComment;
10: use PHPStan\Broker\AnonymousClassNameHelper;
11: use PHPStan\File\FileHelper;
12: use PHPStan\Parser\Parser;
13: use PHPStan\PhpDoc\PhpDocNodeResolver;
14: use PHPStan\PhpDoc\PhpDocStringResolver;
15: use PHPStan\PhpDoc\ResolvedPhpDocBlock;
16: use PHPStan\PhpDoc\Tag\TemplateTag;
17: use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode;
18: use PHPStan\Reflection\ReflectionProvider\ReflectionProviderProvider;
19: use PHPStan\ShouldNotHappenException;
20: use PHPStan\Type\Generic\GenericObjectType;
21: use PHPStan\Type\Generic\TemplateTypeFactory;
22: use PHPStan\Type\Generic\TemplateTypeHelper;
23: use PHPStan\Type\Generic\TemplateTypeMap;
24: use function array_key_exists;
25: use function array_keys;
26: use function array_map;
27: use function array_merge;
28: use function array_pop;
29: use function array_slice;
30: use function count;
31: use function is_array;
32: use function is_callable;
33: use function is_file;
34: use function ltrim;
35: use function md5;
36: use function sprintf;
37: use function strpos;
38: use function strtolower;
39:
40: class FileTypeMapper
41: {
42:
43: private const SKIP_NODE = 1;
44: private const POP_TYPE_MAP_STACK = 2;
45:
46: /** @var NameScope[][] */
47: private array $memoryCache = [];
48:
49: private int $memoryCacheCount = 0;
50:
51: /** @var (false|callable(): NameScope|NameScope)[][] */
52: private array $inProcess = [];
53:
54: /** @var array<string, ResolvedPhpDocBlock> */
55: private array $resolvedPhpDocBlockCache = [];
56:
57: private int $resolvedPhpDocBlockCacheCount = 0;
58:
59: public function __construct(
60: private ReflectionProviderProvider $reflectionProviderProvider,
61: private Parser $phpParser,
62: private PhpDocStringResolver $phpDocStringResolver,
63: private PhpDocNodeResolver $phpDocNodeResolver,
64: private AnonymousClassNameHelper $anonymousClassNameHelper,
65: private FileHelper $fileHelper,
66: )
67: {
68: }
69:
70: /** @api */
71: public function getResolvedPhpDoc(
72: ?string $fileName,
73: ?string $className,
74: ?string $traitName,
75: ?string $functionName,
76: string $docComment,
77: ): ResolvedPhpDocBlock
78: {
79: if ($className === null && $traitName !== null) {
80: throw new ShouldNotHappenException();
81: }
82:
83: if ($docComment === '') {
84: return ResolvedPhpDocBlock::createEmpty();
85: }
86:
87: if ($fileName !== null) {
88: $fileName = $this->fileHelper->normalizePath($fileName);
89: }
90:
91: $nameScopeKey = $this->getNameScopeKey($fileName, $className, $traitName, $functionName);
92: $phpDocKey = md5(sprintf('%s-%s', $nameScopeKey, $docComment));
93: if (isset($this->resolvedPhpDocBlockCache[$phpDocKey])) {
94: return $this->resolvedPhpDocBlockCache[$phpDocKey];
95: }
96:
97: if ($fileName === null) {
98: return $this->createResolvedPhpDocBlock($phpDocKey, new NameScope(null, []), $docComment, null);
99: }
100:
101: $nameScopeMap = [];
102:
103: if (!isset($this->inProcess[$fileName])) {
104: $nameScopeMap = $this->getNameScopeMap($fileName);
105: }
106:
107: if (isset($nameScopeMap[$nameScopeKey])) {
108: return $this->createResolvedPhpDocBlock($phpDocKey, $nameScopeMap[$nameScopeKey], $docComment, $fileName);
109: }
110:
111: if (!isset($this->inProcess[$fileName][$nameScopeKey])) { // wrong $fileName due to traits
112: return ResolvedPhpDocBlock::createEmpty();
113: }
114:
115: if ($this->inProcess[$fileName][$nameScopeKey] === false) { // PHPDoc has cyclic dependency
116: return ResolvedPhpDocBlock::createEmpty();
117: }
118:
119: if (is_callable($this->inProcess[$fileName][$nameScopeKey])) {
120: $resolveCallback = $this->inProcess[$fileName][$nameScopeKey];
121: $this->inProcess[$fileName][$nameScopeKey] = false;
122: $this->inProcess[$fileName][$nameScopeKey] = $resolveCallback();
123: }
124:
125: return $this->createResolvedPhpDocBlock($phpDocKey, $this->inProcess[$fileName][$nameScopeKey], $docComment, $fileName);
126: }
127:
128: private function createResolvedPhpDocBlock(string $phpDocKey, NameScope $nameScope, string $phpDocString, ?string $fileName): ResolvedPhpDocBlock
129: {
130: $phpDocNode = $this->resolvePhpDocStringToDocNode($phpDocString);
131: if ($this->resolvedPhpDocBlockCacheCount >= 2048) {
132: $this->resolvedPhpDocBlockCache = array_slice(
133: $this->resolvedPhpDocBlockCache,
134: 1,
135: null,
136: true,
137: );
138:
139: $this->resolvedPhpDocBlockCacheCount--;
140: }
141:
142: $templateTypeMap = $nameScope->getTemplateTypeMap();
143: $phpDocTemplateTypes = [];
144: $templateTags = $this->phpDocNodeResolver->resolveTemplateTags($phpDocNode, $nameScope);
145: foreach (array_keys($templateTags) as $name) {
146: $templateType = $templateTypeMap->getType($name);
147: if ($templateType === null) {
148: continue;
149: }
150: $phpDocTemplateTypes[$name] = $templateType;
151: }
152:
153: $this->resolvedPhpDocBlockCache[$phpDocKey] = ResolvedPhpDocBlock::create(
154: $phpDocNode,
155: $phpDocString,
156: $fileName,
157: $nameScope,
158: new TemplateTypeMap($phpDocTemplateTypes),
159: $templateTags,
160: $this->phpDocNodeResolver,
161: );
162: $this->resolvedPhpDocBlockCacheCount++;
163:
164: return $this->resolvedPhpDocBlockCache[$phpDocKey];
165: }
166:
167: private function resolvePhpDocStringToDocNode(string $phpDocString): PhpDocNode
168: {
169: return $this->phpDocStringResolver->resolve($phpDocString);
170: }
171:
172: /**
173: * @return NameScope[]
174: */
175: private function getNameScopeMap(string $fileName): array
176: {
177: if (!isset($this->memoryCache[$fileName])) {
178: $map = $this->createResolvedPhpDocMap($fileName);
179: if ($this->memoryCacheCount >= 2048) {
180: $this->memoryCache = array_slice(
181: $this->memoryCache,
182: 1,
183: null,
184: true,
185: );
186: $this->memoryCacheCount--;
187: }
188:
189: $this->memoryCache[$fileName] = $map;
190: $this->memoryCacheCount++;
191: }
192:
193: return $this->memoryCache[$fileName];
194: }
195:
196: /**
197: * @return NameScope[]
198: */
199: private function createResolvedPhpDocMap(string $fileName): array
200: {
201: $nameScopeMap = $this->createNameScopeMap($fileName, null, null, [], $fileName);
202: $resolvedNameScopeMap = [];
203:
204: try {
205: $this->inProcess[$fileName] = $nameScopeMap;
206:
207: foreach ($nameScopeMap as $nameScopeKey => $resolveCallback) {
208: $this->inProcess[$fileName][$nameScopeKey] = false;
209: $this->inProcess[$fileName][$nameScopeKey] = $data = $resolveCallback();
210: $resolvedNameScopeMap[$nameScopeKey] = $data;
211: }
212:
213: } finally {
214: unset($this->inProcess[$fileName]);
215: }
216:
217: return $resolvedNameScopeMap;
218: }
219:
220: /**
221: * @param array<string, string> $traitMethodAliases
222: * @return (callable(): NameScope)[]
223: */
224: private function createNameScopeMap(
225: string $fileName,
226: ?string $lookForTrait,
227: ?string $traitUseClass,
228: array $traitMethodAliases,
229: string $originalClassFileName,
230: ): array
231: {
232: /** @var (callable(): NameScope)[] $nameScopeMap */
233: $nameScopeMap = [];
234:
235: /** @var (callable(): TemplateTypeMap)[] $typeMapStack */
236: $typeMapStack = [];
237:
238: /** @var array<int, array<string, true>> $typeAliasStack */
239: $typeAliasStack = [];
240:
241: /** @var string[] $classStack */
242: $classStack = [];
243: if ($lookForTrait !== null && $traitUseClass !== null) {
244: $classStack[] = $traitUseClass;
245: $typeAliasStack[] = [];
246: }
247: $namespace = null;
248:
249: $traitFound = false;
250:
251: /** @var array<string|null> $functionStack */
252: $functionStack = [];
253: $uses = [];
254: $constUses = [];
255: $this->processNodes(
256: $this->phpParser->parseFile($fileName),
257: function (Node $node) use ($fileName, $lookForTrait, &$traitFound, $traitMethodAliases, $originalClassFileName, &$nameScopeMap, &$classStack, &$typeAliasStack, &$namespace, &$functionStack, &$uses, &$typeMapStack, &$constUses): ?int {
258: if ($node instanceof Node\Stmt\ClassLike) {
259: if ($traitFound && $fileName === $originalClassFileName) {
260: return self::SKIP_NODE;
261: }
262:
263: if ($lookForTrait !== null && !$traitFound) {
264: if (!$node instanceof Node\Stmt\Trait_) {
265: return self::SKIP_NODE;
266: }
267: if ((string) $node->namespacedName !== $lookForTrait) {
268: return self::SKIP_NODE;
269: }
270:
271: $traitFound = true;
272: } else {
273: if ($node->name === null) {
274: if (!$node instanceof Node\Stmt\Class_) {
275: throw new ShouldNotHappenException();
276: }
277:
278: $className = $this->anonymousClassNameHelper->getAnonymousClassName($node, $fileName);
279: } elseif ((bool) $node->getAttribute('anonymousClass', false)) {
280: $className = $node->name->name;
281: } else {
282: if ($traitFound) {
283: return self::SKIP_NODE;
284: }
285: $className = ltrim(sprintf('%s\\%s', $namespace, $node->name->name), '\\');
286: }
287: $classStack[] = $className;
288: $typeAliasStack[] = $this->getTypeAliasesMap($node->getDocComment());
289: $functionStack[] = null;
290: }
291: } elseif ($node instanceof Node\Stmt\ClassMethod) {
292: if (array_key_exists($node->name->name, $traitMethodAliases)) {
293: $functionStack[] = $traitMethodAliases[$node->name->name];
294: } else {
295: $functionStack[] = $node->name->name;
296: }
297: } elseif ($node instanceof Node\Stmt\Function_) {
298: $functionStack[] = ltrim(sprintf('%s\\%s', $namespace, $node->name->name), '\\');
299: }
300:
301: $className = $classStack[count($classStack) - 1] ?? null;
302: $functionName = $functionStack[count($functionStack) - 1] ?? null;
303:
304: if ($node instanceof Node\Stmt\ClassLike || $node instanceof Node\Stmt\ClassMethod || $node instanceof Node\Stmt\Function_) {
305: $phpDocString = GetLastDocComment::forNode($node);
306: if ($phpDocString !== null) {
307: $typeMapStack[] = function () use ($namespace, $uses, $className, $functionName, $phpDocString, $typeMapStack, $constUses): TemplateTypeMap {
308: $phpDocNode = $this->resolvePhpDocStringToDocNode($phpDocString);
309: $typeMapCb = $typeMapStack[count($typeMapStack) - 1] ?? null;
310: $currentTypeMap = $typeMapCb !== null ? $typeMapCb() : null;
311: $nameScope = new NameScope($namespace, $uses, $className, $functionName, $currentTypeMap, [], false, $constUses);
312: $templateTags = $this->phpDocNodeResolver->resolveTemplateTags($phpDocNode, $nameScope);
313: $templateTypeScope = $nameScope->getTemplateTypeScope();
314: if ($templateTypeScope === null) {
315: throw new ShouldNotHappenException();
316: }
317: $templateTypeMap = new TemplateTypeMap(array_map(static fn (TemplateTag $tag): Type => TemplateTypeFactory::fromTemplateTag($templateTypeScope, $tag), $templateTags));
318: $nameScope = $nameScope->withTemplateTypeMap($templateTypeMap);
319: $templateTags = $this->phpDocNodeResolver->resolveTemplateTags($phpDocNode, $nameScope);
320: $templateTypeMap = new TemplateTypeMap(array_map(static fn (TemplateTag $tag): Type => TemplateTypeFactory::fromTemplateTag($templateTypeScope, $tag), $templateTags));
321:
322: return new TemplateTypeMap(array_merge(
323: $currentTypeMap !== null ? $currentTypeMap->getTypes() : [],
324: $templateTypeMap->getTypes(),
325: ));
326: };
327: }
328: }
329:
330: $typeMapCb = $typeMapStack[count($typeMapStack) - 1] ?? null;
331: $typeAliasesMap = $typeAliasStack[count($typeAliasStack) - 1] ?? [];
332:
333: $nameScopeKey = $this->getNameScopeKey($originalClassFileName, $className, $lookForTrait, $functionName);
334: if (
335: $node instanceof Node\Stmt
336: && !$node instanceof Node\Stmt\Namespace_
337: && !$node instanceof Node\Stmt\Declare_
338: && !$node instanceof Node\Stmt\DeclareDeclare
339: && !$node instanceof Node\Stmt\Use_
340: && !$node instanceof Node\Stmt\UseUse
341: && !$node instanceof Node\Stmt\GroupUse
342: && !$node instanceof Node\Stmt\TraitUse
343: && !$node instanceof Node\Stmt\TraitUseAdaptation
344: && !$node instanceof Node\Stmt\InlineHTML
345: && !($node instanceof Node\Stmt\Expression && $node->expr instanceof Node\Expr\Include_)
346: && !array_key_exists($nameScopeKey, $nameScopeMap)
347: ) {
348: $nameScopeMap[$nameScopeKey] = static fn (): NameScope => new NameScope(
349: $namespace,
350: $uses,
351: $className,
352: $functionName,
353: ($typeMapCb !== null ? $typeMapCb() : TemplateTypeMap::createEmpty()),
354: $typeAliasesMap,
355: false,
356: $constUses,
357: );
358: }
359:
360: if ($node instanceof Node\Stmt\ClassLike || $node instanceof Node\Stmt\ClassMethod || $node instanceof Node\Stmt\Function_) {
361: $phpDocString = GetLastDocComment::forNode($node);
362: if ($phpDocString !== null) {
363: return self::POP_TYPE_MAP_STACK;
364: }
365:
366: return null;
367: }
368:
369: if ($node instanceof Node\Stmt\Namespace_) {
370: $namespace = $node->name !== null ? (string) $node->name : null;
371: } elseif ($node instanceof Node\Stmt\Use_) {
372: if ($node->type === Node\Stmt\Use_::TYPE_NORMAL) {
373: foreach ($node->uses as $use) {
374: $uses[strtolower($use->getAlias()->name)] = (string) $use->name;
375: }
376: } elseif ($node->type === Node\Stmt\Use_::TYPE_CONSTANT) {
377: foreach ($node->uses as $use) {
378: $constUses[strtolower($use->getAlias()->name)] = (string) $use->name;
379: }
380: }
381: } elseif ($node instanceof Node\Stmt\GroupUse) {
382: $prefix = (string) $node->prefix;
383: foreach ($node->uses as $use) {
384: if ($node->type === Node\Stmt\Use_::TYPE_NORMAL || $use->type === Node\Stmt\Use_::TYPE_NORMAL) {
385: $uses[strtolower($use->getAlias()->name)] = sprintf('%s\\%s', $prefix, (string) $use->name);
386: } elseif ($node->type === Node\Stmt\Use_::TYPE_CONSTANT || $use->type === Node\Stmt\Use_::TYPE_CONSTANT) {
387: $constUses[strtolower($use->getAlias()->name)] = sprintf('%s\\%s', $prefix, (string) $use->name);
388: }
389: }
390: } elseif ($node instanceof Node\Stmt\TraitUse) {
391: $traitMethodAliases = [];
392: foreach ($node->adaptations as $traitUseAdaptation) {
393: if (!$traitUseAdaptation instanceof Node\Stmt\TraitUseAdaptation\Alias) {
394: continue;
395: }
396:
397: if ($traitUseAdaptation->trait === null) {
398: continue;
399: }
400:
401: if ($traitUseAdaptation->newName === null) {
402: continue;
403: }
404:
405: $traitMethodAliases[$traitUseAdaptation->trait->toString()][$traitUseAdaptation->method->toString()] = $traitUseAdaptation->newName->toString();
406: }
407:
408: $useDocComment = null;
409: if ($node->getDocComment() !== null) {
410: $useDocComment = $node->getDocComment()->getText();
411: }
412:
413: foreach ($node->traits as $traitName) {
414: /** @var class-string $traitName */
415: $traitName = (string) $traitName;
416: $reflectionProvider = $this->reflectionProviderProvider->getReflectionProvider();
417: if (!$reflectionProvider->hasClass($traitName)) {
418: continue;
419: }
420:
421: $traitReflection = $reflectionProvider->getClass($traitName);
422: if (!$traitReflection->isTrait()) {
423: continue;
424: }
425: if ($traitReflection->getFileName() === null) {
426: continue;
427: }
428: if (!is_file($traitReflection->getFileName())) {
429: continue;
430: }
431:
432: $className = $classStack[count($classStack) - 1] ?? null;
433: if ($className === null) {
434: throw new ShouldNotHappenException();
435: }
436:
437: $traitPhpDocMap = $this->createNameScopeMap(
438: $traitReflection->getFileName(),
439: $traitName,
440: $className,
441: $traitMethodAliases[$traitName] ?? [],
442: $originalClassFileName,
443: );
444: $finalTraitPhpDocMap = [];
445: foreach ($traitPhpDocMap as $nameScopeTraitKey => $callback) {
446: $finalTraitPhpDocMap[$nameScopeTraitKey] = function () use ($callback, $traitReflection, $fileName, $className, $lookForTrait, $useDocComment): NameScope {
447: /** @var NameScope $original */
448: $original = $callback();
449: if (!$traitReflection->isGeneric()) {
450: return $original;
451: }
452:
453: $traitTemplateTypeMap = $traitReflection->getTemplateTypeMap();
454:
455: $useType = null;
456: if ($useDocComment !== null) {
457: $useTags = $this->getResolvedPhpDoc(
458: $fileName,
459: $className,
460: $lookForTrait,
461: null,
462: $useDocComment,
463: )->getUsesTags();
464: foreach ($useTags as $useTag) {
465: $useTagType = $useTag->getType();
466: if (!$useTagType instanceof GenericObjectType) {
467: continue;
468: }
469:
470: if ($useTagType->getClassName() !== $traitReflection->getName()) {
471: continue;
472: }
473:
474: $useType = $useTagType;
475: break;
476: }
477: }
478:
479: if ($useType === null) {
480: return $original->withTemplateTypeMap($traitTemplateTypeMap->resolveToBounds());
481: }
482:
483: $transformedTraitTypeMap = $traitReflection->typeMapFromList($useType->getTypes());
484:
485: return $original->withTemplateTypeMap($traitTemplateTypeMap->map(static fn (string $name, Type $type): Type => TemplateTypeHelper::resolveTemplateTypes($type, $transformedTraitTypeMap)));
486: };
487: }
488: $nameScopeMap = array_merge($nameScopeMap, $finalTraitPhpDocMap);
489: }
490: }
491:
492: return null;
493: },
494: static function (Node $node, $callbackResult) use ($lookForTrait, &$namespace, &$functionStack, &$classStack, &$typeAliasStack, &$uses, &$typeMapStack, &$constUses): void {
495: if ($node instanceof Node\Stmt\ClassLike && $lookForTrait === null) {
496: if (count($classStack) === 0) {
497: throw new ShouldNotHappenException();
498: }
499: array_pop($classStack);
500:
501: if (count($typeAliasStack) === 0) {
502: throw new ShouldNotHappenException();
503: }
504:
505: array_pop($typeAliasStack);
506:
507: if (count($functionStack) === 0) {
508: throw new ShouldNotHappenException();
509: }
510:
511: array_pop($functionStack);
512: } elseif ($node instanceof Node\Stmt\Namespace_) {
513: $namespace = null;
514: $uses = [];
515: $constUses = [];
516: } elseif ($node instanceof Node\Stmt\ClassMethod || $node instanceof Node\Stmt\Function_) {
517: if (count($functionStack) === 0) {
518: throw new ShouldNotHappenException();
519: }
520:
521: array_pop($functionStack);
522: }
523: if ($callbackResult !== self::POP_TYPE_MAP_STACK) {
524: return;
525: }
526:
527: if (count($typeMapStack) === 0) {
528: throw new ShouldNotHappenException();
529: }
530: array_pop($typeMapStack);
531: },
532: );
533:
534: if (count($typeMapStack) > 0) {
535: throw new ShouldNotHappenException();
536: }
537:
538: return $nameScopeMap;
539: }
540:
541: /**
542: * @return array<string, true>
543: */
544: private function getTypeAliasesMap(?Doc $docComment): array
545: {
546: if ($docComment === null) {
547: return [];
548: }
549:
550: $phpDocNode = $this->phpDocStringResolver->resolve($docComment->getText());
551: $nameScope = new NameScope(null, []);
552:
553: $aliasesMap = [];
554: foreach (array_keys($this->phpDocNodeResolver->resolveTypeAliasImportTags($phpDocNode, $nameScope)) as $key) {
555: $aliasesMap[$key] = true;
556: }
557:
558: foreach (array_keys($this->phpDocNodeResolver->resolveTypeAliasTags($phpDocNode, $nameScope)) as $key) {
559: $aliasesMap[$key] = true;
560: }
561:
562: return $aliasesMap;
563: }
564:
565: /**
566: * @param Node[]|Node|scalar|null $node
567: * @param Closure(Node $node): mixed $nodeCallback
568: * @param Closure(Node $node, mixed $callbackResult): void $endNodeCallback
569: */
570: private function processNodes($node, Closure $nodeCallback, Closure $endNodeCallback): void
571: {
572: if ($node instanceof Node) {
573: $callbackResult = $nodeCallback($node);
574: if ($callbackResult === self::SKIP_NODE) {
575: return;
576: }
577: foreach ($node->getSubNodeNames() as $subNodeName) {
578: $subNode = $node->{$subNodeName};
579: $this->processNodes($subNode, $nodeCallback, $endNodeCallback);
580: }
581: $endNodeCallback($node, $callbackResult);
582: } elseif (is_array($node)) {
583: foreach ($node as $subNode) {
584: $this->processNodes($subNode, $nodeCallback, $endNodeCallback);
585: }
586: }
587: }
588:
589: private function getNameScopeKey(
590: ?string $file,
591: ?string $class,
592: ?string $trait,
593: ?string $function,
594: ): string
595: {
596: if ($class === null && $trait === null && $function === null) {
597: return md5(sprintf('%s', $file ?? 'no-file'));
598: }
599:
600: if ($class !== null && strpos($class, 'class@anonymous') !== false) {
601: throw new ShouldNotHappenException('Wrong anonymous class name, FilTypeMapper should be called with ClassReflection::getName().');
602: }
603:
604: return md5(sprintf('%s-%s-%s-%s', $file ?? 'no-file', $class, $trait, $function));
605: }
606:
607: }
608: