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