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\IntermediaryNameScope;
9: use PHPStan\Analyser\NameScope;
10: use PHPStan\Analyser\NamespaceUsesTracker;
11: use PHPStan\BetterReflection\Util\GetLastDocComment;
12: use PHPStan\Broker\AnonymousClassNameHelper;
13: use PHPStan\Cache\Cache;
14: use PHPStan\DependencyInjection\AutowiredParameter;
15: use PHPStan\DependencyInjection\AutowiredService;
16: use PHPStan\File\FileContentHasher;
17: use PHPStan\File\FileHelper;
18: use PHPStan\Internal\ComposerHelper;
19: use PHPStan\Internal\LruCache;
20: use PHPStan\Parser\Parser;
21: use PHPStan\Parser\PathRoutingParser;
22: use PHPStan\PhpDoc\NameScopeAlreadyBeingCreatedException;
23: use PHPStan\PhpDoc\PhpDocNodeResolver;
24: use PHPStan\PhpDoc\PhpDocStringResolver;
25: use PHPStan\PhpDoc\ResolvedPhpDocBlock;
26: use PHPStan\PhpDoc\Tag\TemplateTag;
27: use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode;
28: use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode;
29: use PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode;
30: use PHPStan\Reflection\ReflectionProvider\ReflectionProviderProvider;
31: use PHPStan\ShouldNotHappenException;
32: use PHPStan\Type\Generic\GenericObjectType;
33: use PHPStan\Type\Generic\TemplateTypeFactory;
34: use PHPStan\Type\Generic\TemplateTypeHelper;
35: use PHPStan\Type\Generic\TemplateTypeMap;
36: use PHPStan\Type\Generic\TemplateTypeVariance;
37: use PHPStan\Type\Generic\TemplateTypeVarianceMap;
38: use function array_key_exists;
39: use function array_key_first;
40: use function array_keys;
41: use function array_last;
42: use function array_map;
43: use function array_merge;
44: use function array_pop;
45: use function array_reverse;
46: use function count;
47: use function in_array;
48: use function is_array;
49: use function is_file;
50: use function ltrim;
51: use function md5;
52: use function sprintf;
53: use function str_contains;
54: use function str_starts_with;
55:
56: #[AutowiredService]
57: final class FileTypeMapper
58: {
59:
60: private const SKIP_NODE = 1;
61: private const POP_TYPE_MAP_STACK = 2;
62:
63: /** @var LruCache<array{array<string, IntermediaryNameScope>}> */
64: private LruCache $memoryCache;
65:
66: /** @var array<string, true> */
67: private array $inProcess = [];
68:
69: /** @var array<string, NameScope> */
70: private array $inProcessNameScopes = [];
71:
72: /** @var array<string, int> */
73: private array $classNameScopesBeingCreated = [];
74:
75: /** @var array<string, ResolvedPhpDocBlock> */
76: private array $resolvedPhpDocBlockCache = [];
77:
78: private int $resolvedPhpDocBlockCacheCount = 0;
79:
80: public function __construct(
81: private ReflectionProviderProvider $reflectionProviderProvider,
82: #[AutowiredParameter(ref: '@defaultAnalysisParser')]
83: private Parser $phpParser,
84: private PhpDocStringResolver $phpDocStringResolver,
85: private PhpDocNodeResolver $phpDocNodeResolver,
86: private AnonymousClassNameHelper $anonymousClassNameHelper,
87: private FileHelper $fileHelper,
88: private Cache $cache,
89: private FileContentHasher $fileContentHasher,
90: #[AutowiredParameter(ref: '%cache.resolvedPhpDocBlockCacheCountMax%')]
91: private int $resolvedPhpDocBlockCacheCountMax,
92: #[AutowiredParameter(ref: '%cache.nameScopeMapMemoryCacheCountMax%')]
93: int $nameScopeMapMemoryCacheCountMax,
94: )
95: {
96: // 0 kept one entry here rather than meaning "no limit" as it does for the other bounded
97: // caches: the eviction loop ran before the insertion, emptying the cache and then putting
98: // a single entry back. Preserved rather than normalised - see the PR description.
99: $this->memoryCache = new LruCache($nameScopeMapMemoryCacheCountMax === 0 ? 1 : $nameScopeMapMemoryCacheCountMax);
100: }
101:
102: /** @api */
103: public function getResolvedPhpDoc(
104: ?string $fileName,
105: ?string $className,
106: ?string $traitName,
107: ?string $functionName,
108: ?string $docComment,
109: ): ResolvedPhpDocBlock
110: {
111: if ($className === null && $traitName !== null) {
112: throw new ShouldNotHappenException();
113: }
114:
115: if (in_array($docComment, [null, ''], true)) {
116: return ResolvedPhpDocBlock::createEmpty();
117: }
118:
119: if ($fileName !== null) {
120: $fileName = $this->fileHelper->normalizePath($fileName);
121: }
122:
123: $nameScopeKey = $this->getNameScopeKey($fileName, $className, $traitName, $functionName);
124: $phpDocKey = $this->getPhpDocKey($nameScopeKey, $docComment);
125: if (isset($this->resolvedPhpDocBlockCache[$phpDocKey])) {
126: return $this->resolvedPhpDocBlockCache[$phpDocKey];
127: }
128:
129: while ($this->resolvedPhpDocBlockCacheCount >= $this->resolvedPhpDocBlockCacheCountMax) {
130: $oldestKey = array_key_first($this->resolvedPhpDocBlockCache);
131: if ($oldestKey === null) {
132: break;
133: }
134: unset($this->resolvedPhpDocBlockCache[$oldestKey]);
135: $this->resolvedPhpDocBlockCacheCount--;
136: }
137:
138: $this->resolvedPhpDocBlockCacheCount++;
139:
140: if ($fileName === null) {
141: return $this->resolvedPhpDocBlockCache[$phpDocKey] = $this->createResolvedPhpDocBlock($this->phpDocStringResolver->resolve($docComment), new NameScope(null, []), $docComment, null);
142: }
143:
144: try {
145: $nameScope = $this->getNameScope($fileName, $className, $traitName, $functionName);
146: } catch (NameScopeAlreadyBeingCreatedException) {
147: return $this->resolvedPhpDocBlockCache[$phpDocKey] = ResolvedPhpDocBlock::createEmpty();
148: }
149:
150: return $this->resolvedPhpDocBlockCache[$phpDocKey] = $this->createResolvedPhpDocBlock(
151: $this->phpDocStringResolver->resolve($docComment),
152: $nameScope,
153: $docComment,
154: $fileName,
155: );
156: }
157:
158: /**
159: * While a class's name scope is being created, the PHPDoc resolved for that class
160: * does not have its template tags yet.
161: */
162: public function isClassNameScopeBeingCreated(string $className): bool
163: {
164: return isset($this->classNameScopesBeingCreated[$className]);
165: }
166:
167: private function createResolvedPhpDocBlock(
168: PhpDocNode $phpDocNode,
169: NameScope $nameScope,
170: string $phpDocString,
171: ?string $fileName,
172: ): ResolvedPhpDocBlock
173: {
174: $docBlockTemplateTypes = [];
175: $templateTypeMap = $nameScope->getTemplateTypeMap();
176: $templateTags = [];
177: $phpDocNodeTemplateTagsByName = [];
178: foreach ($phpDocNode->getTags() as $tagNode) {
179: $valueNode = $tagNode->value;
180: if (!$valueNode instanceof TemplateTagValueNode) {
181: continue;
182: }
183:
184: $phpDocNodeTemplateTagsByName[$valueNode->name] = true;
185: }
186: foreach ($nameScope->getTemplateTags() as $templateTagName => $templateTag) {
187: if (!array_key_exists($templateTagName, $phpDocNodeTemplateTagsByName)) {
188: continue;
189: }
190: $templateTags[$templateTagName] = $templateTag;
191: $templateType = $templateTypeMap->getType($templateTagName);
192: if ($templateType === null) {
193: continue;
194: }
195: $docBlockTemplateTypes[$templateTagName] = $templateType;
196: }
197:
198: return ResolvedPhpDocBlock::create(
199: $phpDocNode,
200: $phpDocString,
201: $fileName,
202: $nameScope,
203: new TemplateTypeMap($docBlockTemplateTypes),
204: $templateTags,
205: $this->phpDocNodeResolver,
206: $this->reflectionProviderProvider->getReflectionProvider(),
207: );
208: }
209:
210: /**
211: * The lexical part of a name scope - the namespace and the uses a PHPDoc's names resolve
212: * against. Unlike getNameScope() it does not resolve the surrounding @template bounds, which
213: * goes through TypeNodeResolver and the ReflectionProvider. A caller that only needs to know
214: * how the names in a PHPDoc text are spelled out should ask for this one.
215: */
216: public function getIntermediaryNameScope(
217: string $fileName,
218: ?string $className,
219: ?string $traitName,
220: ?string $functionName,
221: ): ?IntermediaryNameScope
222: {
223: $fileName = $this->fileHelper->normalizePath($fileName);
224: $nameScopeKey = $this->getNameScopeKey($fileName, $className, $traitName, $functionName);
225: [$nameScopeMap] = $this->getNameScopeMap($fileName);
226:
227: return $nameScopeMap[$nameScopeKey] ?? null;
228: }
229:
230: /**
231: * @throws NameScopeAlreadyBeingCreatedException
232: */
233: public function getNameScope(
234: string $fileName,
235: ?string $className,
236: ?string $traitName,
237: ?string $functionName,
238: ): NameScope
239: {
240: $nameScopeKey = $this->getNameScopeKey($fileName, $className, $traitName, $functionName);
241: if (isset($this->inProcess[$nameScopeKey])) {
242: if (isset($this->inProcessNameScopes[$nameScopeKey])) {
243: return $this->inProcessNameScopes[$nameScopeKey];
244: }
245: throw new NameScopeAlreadyBeingCreatedException();
246: }
247:
248: [$nameScopeMap] = $this->getNameScopeMap($fileName);
249: if (!isset($nameScopeMap[$nameScopeKey])) {
250: throw new NameScopeAlreadyBeingCreatedException();
251: }
252:
253: $intermediaryNameScope = $nameScopeMap[$nameScopeKey];
254:
255: $this->inProcess[$nameScopeKey] = true;
256: $classNameScope = $className !== null && $traitName === null && $functionName === null ? $className : null;
257: if ($classNameScope !== null) {
258: $this->classNameScopesBeingCreated[$classNameScope] = ($this->classNameScopesBeingCreated[$classNameScope] ?? 0) + 1;
259: }
260:
261: try {
262: $parents = [$intermediaryNameScope];
263: $i = $intermediaryNameScope;
264: while ($i->getParent() !== null) {
265: $parents[] = $i->getParent();
266: $i = $i->getParent();
267: }
268:
269: $phpDocTemplateTypes = [];
270: $templateTags = [];
271: $reflectionProvider = $this->reflectionProviderProvider->getReflectionProvider();
272: foreach (array_reverse($parents) as $parent) {
273: $nameScope = new NameScope(
274: $parent->getNamespace(),
275: $parent->getUses(),
276: $parent->getClassName(),
277: $parent->getFunctionName(),
278: new TemplateTypeMap($phpDocTemplateTypes),
279: $templateTags,
280: $parent->getTypeAliasesMap(),
281: $parent->shouldBypassTypeAliases(),
282: $parent->getConstUses(),
283: $parent->getClassNameForTypeAlias(),
284: $fileName,
285: );
286: if ($parent->getTraitData() !== null) {
287: [$traitFileName, $traitClassName, $traitName, $lookForTraitName, $traitDocComment] = $parent->getTraitData();
288: if (!$reflectionProvider->hasClass($traitName)) {
289: continue;
290: }
291: $traitReflection = $reflectionProvider->getClass($traitName);
292: $useTags = $this->getResolvedPhpDoc(
293: $traitFileName,
294: $traitClassName,
295: $lookForTraitName,
296: null,
297: $traitDocComment,
298: )->getUsesTags();
299: $useType = null;
300: foreach ($useTags as $useTag) {
301: $useTagType = $useTag->getType();
302: if (!$useTagType instanceof GenericObjectType) {
303: continue;
304: }
305:
306: if ($useTagType->getClassName() !== $traitReflection->getName()) {
307: continue;
308: }
309:
310: $useType = $useTagType;
311: break;
312: }
313: $traitTemplateTypeMap = $traitReflection->getTemplateTypeMap();
314: $namesToUnset = [];
315: if ($useType === null) {
316: foreach ($traitTemplateTypeMap->resolveToBounds()->getTypes() as $name => $templateType) {
317: $phpDocTemplateTypes[$name] = $templateType;
318: $namesToUnset[] = $name;
319: }
320: } else {
321: $transformedTraitTypeMap = $traitReflection->typeMapFromList($useType->getTypes());
322: $nameScopeTemplateTypeMap = $traitTemplateTypeMap->map(
323: static fn (string $name, Type $type): Type => TemplateTypeHelper::resolveTemplateTypes($type, $transformedTraitTypeMap, TemplateTypeVarianceMap::createEmpty(), TemplateTypeVariance::createStatic()),
324: );
325: foreach ($nameScopeTemplateTypeMap->getTypes() as $name => $templateType) {
326: $phpDocTemplateTypes[$name] = $templateType;
327: $namesToUnset[] = $name;
328: }
329: }
330: $parent = $parent->unsetTemplatePhpDocNodes($namesToUnset);
331: }
332:
333: $templateTypeScope = $nameScope->getTemplateTypeScope();
334: if ($templateTypeScope === null) {
335: continue;
336: }
337:
338: $this->inProcessNameScopes[$nameScopeKey] = $nameScope;
339:
340: $templateTags = $this->phpDocNodeResolver->resolveTemplateTags($parent->getTemplatePhpDocNodes(), $nameScope);
341: $templateTypeMap = new TemplateTypeMap(array_map(static fn (TemplateTag $tag): Type => TemplateTypeFactory::fromTemplateTag($templateTypeScope, $tag), $templateTags));
342: $nameScope = $nameScope->withTemplateTypeMap($templateTypeMap, $templateTags);
343: $templateTags = $this->phpDocNodeResolver->resolveTemplateTags($parent->getTemplatePhpDocNodes(), $nameScope);
344: $templateTypeMap = new TemplateTypeMap(array_map(static fn (TemplateTag $tag): Type => TemplateTypeFactory::fromTemplateTag($templateTypeScope, $tag), $templateTags));
345: $nameScope = $nameScope->withTemplateTypeMap($templateTypeMap, $templateTags);
346: $templateTags = $this->phpDocNodeResolver->resolveTemplateTags($parent->getTemplatePhpDocNodes(), $nameScope);
347: $templateTypeMap = new TemplateTypeMap(array_map(static fn (TemplateTag $tag): Type => TemplateTypeFactory::fromTemplateTag($templateTypeScope, $tag), $templateTags));
348: foreach (array_keys($templateTags) as $name) {
349: $templateType = $templateTypeMap->getType($name);
350: if ($templateType === null) {
351: continue;
352: }
353: $phpDocTemplateTypes[$name] = $templateType;
354: }
355: }
356:
357: return new NameScope(
358: $intermediaryNameScope->getNamespace(),
359: $intermediaryNameScope->getUses(),
360: $intermediaryNameScope->getClassName(),
361: $intermediaryNameScope->getFunctionName(),
362: new TemplateTypeMap($phpDocTemplateTypes),
363: $templateTags,
364: $intermediaryNameScope->getTypeAliasesMap(),
365: $intermediaryNameScope->shouldBypassTypeAliases(),
366: $intermediaryNameScope->getConstUses(),
367: $intermediaryNameScope->getClassNameForTypeAlias(),
368: $fileName,
369: );
370: } finally {
371: unset($this->inProcess[$nameScopeKey]);
372: unset($this->inProcessNameScopes[$nameScopeKey]);
373: if ($classNameScope !== null && --$this->classNameScopesBeingCreated[$classNameScope] === 0) {
374: unset($this->classNameScopesBeingCreated[$classNameScope]);
375: }
376: }
377: }
378:
379: /**
380: * @return array{array<string, IntermediaryNameScope>}
381: */
382: private function getNameScopeMap(string $fileName): array
383: {
384: $cachedEntry = $this->memoryCache->get($fileName);
385: if ($cachedEntry !== null) {
386: return $cachedEntry;
387: }
388:
389: // a map built from the simplified AST of a file outside the analysed paths lacks
390: // the name scopes of classes declared inside function bodies, so it must not be
391: // reused once the file gets analysed, nor the other way around
392: $cacheKey = sprintf('ftm-%s%s', $this->returnsSimplifiedAst($fileName) ? 'simplified-' : '', $fileName);
393: // v6: v5 entries may be poisoned by the turbo comment-loss bug
394: // (https://github.com/phpstan/phpstan/issues/15037) - a parse that
395: // silently dropped every comment cached PHPDoc-less name-scope maps,
396: // and the content hashes cannot tell them apart from real ones.
397: // v7: IntermediaryNameScope refers to a NamespaceUses shared with the other name scopes
398: // created under the same use statements
399: // v8: the files are recorded with whether the map was built from their simplified AST;
400: // v7 entries may be built from it even under the key of the full AST
401: $variableCacheKey = sprintf('v8-%s', ComposerHelper::getPhpDocParserVersion());
402: $cached = $this->loadCachedPhpDocNodeMap($cacheKey, $variableCacheKey);
403: if ($cached === null) {
404: [$nameScopeMap, $files] = $this->createPhpDocNodeMap($fileName, null, null, [], $fileName);
405: $filesWithHashes = [];
406: foreach ($files as $file) {
407: $newHash = $this->fileContentHasher->hash($file);
408: $filesWithHashes[$file] = [$newHash, $this->returnsSimplifiedAst($file)];
409: }
410: $this->cache->save($cacheKey, $variableCacheKey, [$nameScopeMap, $filesWithHashes]);
411: } else {
412: [$nameScopeMap] = $cached;
413: }
414: $entry = [$nameScopeMap];
415: $this->memoryCache->set($fileName, $entry, 0);
416:
417: return $entry;
418: }
419:
420: /**
421: * @param non-empty-string $cacheKey
422: * @return array{array<string, IntermediaryNameScope>, list<string>}|null
423: */
424: private function loadCachedPhpDocNodeMap(string $cacheKey, string $variableCacheKey): ?array
425: {
426: $cached = $this->cache->load($cacheKey, $variableCacheKey);
427: if ($cached !== null) {
428: /**
429: * @var array<string, array{string, bool}> $filesWithHashes
430: */
431: [$nameScopeMap, $filesWithHashes] = $cached;
432: $useCache = true;
433: foreach ($filesWithHashes as $file => [$hash, $simplifiedAst]) {
434: $newHash = $this->fileContentHasher->hash($file);
435: if ($newHash === false) {
436: $useCache = false;
437: break;
438: }
439: if ($newHash === $hash && $this->returnsSimplifiedAst($file) === $simplifiedAst) {
440: continue;
441: }
442: $useCache = false;
443: break;
444: }
445:
446: if ($useCache) {
447: return [$nameScopeMap, array_keys($filesWithHashes)];
448: }
449: }
450:
451: return null;
452: }
453:
454: private function returnsSimplifiedAst(string $fileName): bool
455: {
456: return $this->phpParser instanceof PathRoutingParser && $this->phpParser->returnsSimplifiedAst($fileName);
457: }
458:
459: /**
460: * @param array<string, string> $traitMethodAliases
461: * @param array<string, true> $activeTraitResolutions
462: * @return array{array<string, IntermediaryNameScope>, list<string>}
463: */
464: private function createPhpDocNodeMap(string $fileName, ?string $lookForTrait, ?string $traitUseClass, array $traitMethodAliases, string $originalClassFileName, array $activeTraitResolutions = []): array
465: {
466: /** @var array<string, IntermediaryNameScope> $nameScopeMap */
467: $nameScopeMap = [];
468:
469: /** @var array<int, IntermediaryNameScope> $typeMapStack */
470: $typeMapStack = [];
471:
472: /** @var array<int, array<string, true>> $typeAliasStack */
473: $typeAliasStack = [];
474:
475: /** @var string[] $classStack */
476: $classStack = [];
477: if ($lookForTrait !== null && $traitUseClass !== null) {
478: $classStack[] = $traitUseClass;
479: $typeAliasStack[] = [];
480: }
481: $namespaceUsesTracker = new NamespaceUsesTracker();
482:
483: $traitFound = false;
484:
485: $files = [$fileName];
486:
487: /** @var array<string|null> $functionStack */
488: $functionStack = [];
489: $this->processNodes(
490: $this->phpParser->parseFile($fileName),
491: function (Node $node) use ($fileName, $lookForTrait, &$traitFound, $traitMethodAliases, $originalClassFileName, $activeTraitResolutions, &$nameScopeMap, &$typeMapStack, &$typeAliasStack, &$classStack, $namespaceUsesTracker, &$functionStack, &$files): ?int {
492: $namespaceUsesTracker->enterNode($node);
493: if ($node instanceof Node\Stmt\ClassLike) {
494: if ($traitFound && $fileName === $originalClassFileName) {
495: return self::SKIP_NODE;
496: }
497:
498: if ($lookForTrait !== null && !$traitFound) {
499: if (!$node instanceof Node\Stmt\Trait_) {
500: return self::SKIP_NODE;
501: }
502: if ((string) $node->namespacedName !== $lookForTrait) {
503: return self::SKIP_NODE;
504: }
505:
506: $traitFound = true;
507: $functionStack[] = null;
508: } else {
509: if ($node->name === null) {
510: if (!$node instanceof Node\Stmt\Class_) {
511: throw new ShouldNotHappenException();
512: }
513:
514: $className = $this->anonymousClassNameHelper->getAnonymousClassName($node, $fileName);
515: } elseif ($node instanceof Node\Stmt\Class_ && $node->isAnonymous()) {
516: $className = $node->name->name;
517: } else {
518: if ($traitFound) {
519: return self::SKIP_NODE;
520: }
521: $className = ltrim(sprintf('%s\\%s', $namespaceUsesTracker->getNamespaceUses()->getNamespace(), $node->name->name), '\\');
522: }
523: $classStack[] = $className;
524: $functionStack[] = null;
525: }
526: } elseif ($node instanceof Node\Stmt\ClassMethod) {
527: if (array_key_exists($node->name->name, $traitMethodAliases)) {
528: $functionStack[] = $traitMethodAliases[$node->name->name];
529: } else {
530: $functionStack[] = $node->name->name;
531: }
532: } elseif ($node instanceof Node\Stmt\Function_) {
533: $functionStack[] = ltrim(sprintf('%s\\%s', $namespaceUsesTracker->getNamespaceUses()->getNamespace(), $node->name->name), '\\');
534: } elseif ($node instanceof Node\PropertyHook) {
535: $propertyName = $node->getAttribute('propertyName');
536: if ($propertyName !== null) {
537: $functionStack[] = sprintf('$%s::%s', $propertyName, $node->name->toString());
538: }
539: }
540:
541: $className = array_last($classStack);
542: $functionName = array_last($functionStack);
543: $nameScopeKey = $this->getNameScopeKey($originalClassFileName, $className, $lookForTrait, $functionName);
544:
545: $phpDocNode = null;
546: $docComment = null;
547: if (
548: $node instanceof Node\Stmt
549: || ($node instanceof Node\PropertyHook && $node->getAttribute('propertyName') !== null)
550: ) {
551: $docComment = GetLastDocComment::forNode($node);
552: if ($docComment !== null) {
553: $phpDocNode = $this->phpDocStringResolver->resolve($docComment);
554: }
555: }
556:
557: if ($node instanceof Node\Stmt\ClassLike || $node instanceof Node\Stmt\ClassMethod || $node instanceof Node\Stmt\Function_ || $node instanceof Node\PropertyHook) {
558: if ($phpDocNode !== null) {
559: if ($node instanceof Node\Stmt\ClassLike) {
560: $typeAliasStack[] = $this->getTypeAliasesMap($phpDocNode);
561: }
562:
563: $parentNameScope = array_last($typeMapStack);
564:
565: $typeMapStack[] = new IntermediaryNameScope(
566: $namespaceUsesTracker->getNamespaceUses(),
567: $className,
568: $functionName,
569: $this->chooseTemplateTagValueNodesByPriority($phpDocNode->getTags()),
570: $parentNameScope,
571: array_last($typeAliasStack) ?? [],
572: typeAliasClassName: $lookForTrait,
573: );
574: } elseif ($node instanceof Node\Stmt\ClassLike) {
575: $typeAliasStack[] = [];
576: } else {
577: $parentNameScope = array_last($typeMapStack);
578: $typeMapStack[] = new IntermediaryNameScope(
579: $namespaceUsesTracker->getNamespaceUses(),
580: $className,
581: $functionName,
582: [],
583: $parentNameScope,
584: array_last($typeAliasStack) ?? [],
585: typeAliasClassName: $lookForTrait,
586: );
587: }
588: }
589:
590: if (
591: (
592: $node instanceof Node\PropertyHook
593: || (
594: $node instanceof Node\Stmt
595: && !$node instanceof Node\Stmt\Namespace_
596: && !$node instanceof Node\Stmt\Declare_
597: && !$node instanceof Node\Stmt\Use_
598: && !$node instanceof Node\Stmt\GroupUse
599: && !$node instanceof Node\Stmt\TraitUse
600: && !$node instanceof Node\Stmt\TraitUseAdaptation
601: && !$node instanceof Node\Stmt\InlineHTML
602: && !($node instanceof Node\Stmt\Expression && $node->expr instanceof Node\Expr\Include_)
603: )
604: ) && !array_key_exists($nameScopeKey, $nameScopeMap)
605: ) {
606: $parentNameScope = array_last($typeMapStack);
607: $typeAliasesMap = array_last($typeAliasStack) ?? [];
608: $nameScopeMap[$nameScopeKey] = new IntermediaryNameScope(
609: $namespaceUsesTracker->getNamespaceUses(),
610: $className,
611: $functionName,
612: $parentNameScope !== null ? $parentNameScope->getTemplatePhpDocNodes() : [],
613: $parentNameScope?->getParent(),
614: $typeAliasesMap,
615: typeAliasClassName: $lookForTrait,
616: );
617: }
618:
619: if ($node instanceof Node\Stmt\ClassLike || $node instanceof Node\Stmt\ClassMethod || $node instanceof Node\Stmt\Function_ || $node instanceof Node\PropertyHook) {
620: if ($phpDocNode !== null || !$node instanceof Node\Stmt\ClassLike) {
621: return self::POP_TYPE_MAP_STACK;
622: }
623:
624: return null;
625: }
626:
627: if ($node instanceof Node\Stmt\TraitUse) {
628: $traitMethodAliases = [];
629: foreach ($node->adaptations as $traitUseAdaptation) {
630: if (!$traitUseAdaptation instanceof Node\Stmt\TraitUseAdaptation\Alias) {
631: continue;
632: }
633:
634: if ($traitUseAdaptation->newName === null) {
635: continue;
636: }
637:
638: $methodName = $traitUseAdaptation->method->toString();
639: $newTraitName = $traitUseAdaptation->newName->toString();
640:
641: if ($traitUseAdaptation->trait === null) {
642: foreach ($node->traits as $traitName) {
643: $traitMethodAliases[$traitName->toString()][$methodName] = $newTraitName;
644: }
645: continue;
646: }
647:
648: $traitMethodAliases[$traitUseAdaptation->trait->toString()][$methodName] = $newTraitName;
649: }
650:
651: foreach ($node->traits as $traitName) {
652: /** @var class-string $traitName */
653: $traitName = (string) $traitName;
654: $reflectionProvider = $this->reflectionProviderProvider->getReflectionProvider();
655: if (!$reflectionProvider->hasClass($traitName)) {
656: continue;
657: }
658:
659: $traitReflection = $reflectionProvider->getClass($traitName);
660: if (!$traitReflection->isTrait()) {
661: continue;
662: }
663: if ($traitReflection->getFileName() === null) {
664: continue;
665: }
666: if (!is_file($traitReflection->getFileName())) {
667: continue;
668: }
669:
670: $className = array_last($classStack);
671: if ($className === null) {
672: throw new ShouldNotHappenException();
673: }
674:
675: $traitResolutionKey = $this->getTraitResolutionKey($traitReflection->getFileName(), $traitName, $className, $originalClassFileName);
676: if (isset($activeTraitResolutions[$traitResolutionKey])) {
677: continue;
678: }
679:
680: $nestedActiveTraitResolutions = $activeTraitResolutions;
681: $nestedActiveTraitResolutions[$traitResolutionKey] = true;
682:
683: [$traitNameScopeMap, $traitFiles] = $this->createPhpDocNodeMap(
684: $traitReflection->getFileName(),
685: $traitName,
686: $className,
687: $traitMethodAliases[$traitName] ?? [],
688: $originalClassFileName,
689: $nestedActiveTraitResolutions,
690: );
691: $nameScopeMap = array_merge($nameScopeMap, array_map(static fn ($originalNameScope) => $originalNameScope->getTraitData() === null ? $originalNameScope->withTraitData($originalClassFileName, $className, $traitName, $lookForTrait, $docComment) : $originalNameScope, $traitNameScopeMap));
692: $files = array_merge($files, $traitFiles);
693: }
694: }
695:
696: return null;
697: },
698: static function (Node $node, $callbackResult) use (&$functionStack, &$classStack, &$typeAliasStack, &$typeMapStack): void {
699: if ($node instanceof Node\Stmt\ClassLike) {
700: if (count($classStack) === 0) {
701: throw new ShouldNotHappenException();
702: }
703: array_pop($classStack);
704:
705: if (count($typeAliasStack) === 0) {
706: throw new ShouldNotHappenException();
707: }
708:
709: array_pop($typeAliasStack);
710:
711: if (count($functionStack) === 0) {
712: throw new ShouldNotHappenException();
713: }
714:
715: array_pop($functionStack);
716: } elseif ($node instanceof Node\Stmt\ClassMethod || $node instanceof Node\Stmt\Function_) {
717: if (count($functionStack) === 0) {
718: throw new ShouldNotHappenException();
719: }
720:
721: array_pop($functionStack);
722: } elseif ($node instanceof Node\PropertyHook) {
723: $propertyName = $node->getAttribute('propertyName');
724: if ($propertyName !== null) {
725: if (count($functionStack) === 0) {
726: throw new ShouldNotHappenException();
727: }
728:
729: array_pop($functionStack);
730: }
731: }
732: if ($callbackResult !== self::POP_TYPE_MAP_STACK) {
733: return;
734: }
735:
736: if (count($typeMapStack) === 0) {
737: throw new ShouldNotHappenException();
738: }
739: array_pop($typeMapStack);
740: },
741: );
742:
743: if (count($typeMapStack) > 0) {
744: throw new ShouldNotHappenException();
745: }
746:
747: return [$nameScopeMap, $files];
748: }
749:
750: /**
751: * @param PhpDocTagNode[] $tags
752: * @return array<string, array{string, TemplateTagValueNode}>
753: */
754: private function chooseTemplateTagValueNodesByPriority(array $tags): array
755: {
756: $resolved = [];
757: $resolvedPrefix = [];
758:
759: $prefixPriority = [
760: '' => 0,
761: 'phan' => 1,
762: 'psalm' => 2,
763: 'phpstan' => 3,
764: ];
765: foreach ($tags as $phpDocTagNode) {
766: $valueNode = $phpDocTagNode->value;
767: if (!$valueNode instanceof TemplateTagValueNode) {
768: continue;
769: }
770:
771: $tagName = $phpDocTagNode->name;
772: if (str_starts_with($tagName, '@phan-')) {
773: $prefix = 'phan';
774: } elseif (str_starts_with($tagName, '@psalm-')) {
775: $prefix = 'psalm';
776: } elseif (str_starts_with($tagName, '@phpstan-')) {
777: $prefix = 'phpstan';
778: } else {
779: $prefix = '';
780: }
781:
782: if (isset($resolved[$valueNode->name])) {
783: $setPrefix = $resolvedPrefix[$valueNode->name];
784: if ($prefixPriority[$prefix] <= $prefixPriority[$setPrefix]) {
785: continue;
786: }
787: }
788:
789: $resolved[$valueNode->name] = [$phpDocTagNode->name, $valueNode];
790: $resolvedPrefix[$valueNode->name] = $prefix;
791: }
792:
793: return $resolved;
794: }
795:
796: /**
797: * @return array<string, true>
798: */
799: private function getTypeAliasesMap(PhpDocNode $phpDocNode): array
800: {
801: $nameScope = new NameScope(null, []);
802:
803: $aliasesMap = [];
804: foreach (array_keys($this->phpDocNodeResolver->resolveTypeAliasImportTags($phpDocNode, $nameScope)) as $key) {
805: $aliasesMap[$key] = true;
806: }
807:
808: foreach (array_keys($this->phpDocNodeResolver->resolveTypeAliasTags($phpDocNode, $nameScope)) as $key) {
809: $aliasesMap[$key] = true;
810: }
811:
812: return $aliasesMap;
813: }
814:
815: /**
816: * @param Node[]|Node|scalar|null $node
817: * @param Closure(Node $node): mixed $nodeCallback
818: * @param Closure(Node $node, mixed $callbackResult): void $endNodeCallback
819: */
820: private function processNodes($node, Closure $nodeCallback, Closure $endNodeCallback): void
821: {
822: if ($node instanceof Node) {
823: $callbackResult = $nodeCallback($node);
824: if ($callbackResult === self::SKIP_NODE) {
825: return;
826: }
827: foreach ($node->getSubNodeNames() as $subNodeName) {
828: $subNode = $node->{$subNodeName};
829: $this->processNodes($subNode, $nodeCallback, $endNodeCallback);
830: }
831: $endNodeCallback($node, $callbackResult);
832: } elseif (is_array($node)) {
833: foreach ($node as $subNode) {
834: $this->processNodes($subNode, $nodeCallback, $endNodeCallback);
835: }
836: }
837: }
838:
839: private function getNameScopeKey(
840: ?string $file,
841: ?string $class,
842: ?string $trait,
843: ?string $function,
844: ): string
845: {
846: if ($class === null && $trait === null && $function === null) {
847: return md5(sprintf('%s', $file ?? 'no-file'));
848: }
849:
850: if ($class !== null && str_contains($class, 'class@anonymous')) {
851: throw new ShouldNotHappenException('Wrong anonymous class name, FilTypeMapper should be called with ClassReflection::getName().');
852: }
853:
854: return md5(sprintf('%s-%s-%s-%s', $file ?? 'no-file', $class, $trait, $function));
855: }
856:
857: private function getPhpDocKey(string $nameScopeKey, string $docComment): string
858: {
859: $doc = new Doc($docComment);
860: return md5(sprintf('%s-%s', $nameScopeKey, $doc->getReformattedText()));
861: }
862:
863: private function getTraitResolutionKey(string $fileName, string $traitName, string $className, string $originalClassFileName): string
864: {
865: return md5(sprintf('%s-%s-%s-%s', $fileName, $traitName, $className, $originalClassFileName));
866: }
867:
868: }
869: