Repository navigation
Expand file tree
/
Copy pathOptimizedDirectorySourceLocator.php
More file actions
430 lines (367 loc) · 13.8 KB
/
Copy pathOptimizedDirectorySourceLocator.php
File metadata and controls
430 lines (367 loc) · 13.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
<?php declare(strict_types = 1);
namespace PHPStan\Reflection\BetterReflection\SourceLocator;
use Override;
use PhpParser\Node;
use PHPStan\BetterReflection\Identifier\Identifier;
use PHPStan\BetterReflection\Identifier\IdentifierType;
use PHPStan\BetterReflection\Reflection\Reflection;
use PHPStan\BetterReflection\Reflection\ReflectionClass;
use PHPStan\BetterReflection\Reflection\ReflectionConstant;
use PHPStan\BetterReflection\Reflection\ReflectionEnum;
use PHPStan\BetterReflection\Reflection\ReflectionFunction;
use PHPStan\BetterReflection\Reflector\Reflector;
use PHPStan\BetterReflection\SourceLocator\Ast\Strategy\NodeToReflection;
use PHPStan\BetterReflection\SourceLocator\Type\SourceLocator;
use PHPStan\Cache\ArenaCache;
use PHPStan\Cache\Cache;
use PHPStan\File\CouldNotReadFileException;
use PHPStan\File\FileContentHasher;
use PHPStan\Internal\ComposerHelper;
use PHPStan\Php\PhpVersion;
use PHPStan\Reflection\ConstantNameHelper;
use PHPStan\ShouldNotHappenException;
use function array_key_exists;
use function array_values;
use function current;
use function is_array;
use function is_string;
use function sprintf;
use function strtolower;
final class OptimizedDirectorySourceLocator implements SourceLocator
{
/** @var array<string, string|false> */
private array $arenaClassLookups = [];
/** @var array<string, array<int, string>|false> */
private array $arenaFunctionLookups = [];
/** @var array<string, string|false> */
private array $arenaConstantLookups = [];
private bool $hydratedFromArena = false;
/**
* With $arenaKeyPrefix set, the maps start empty and names resolve lazily
* from the run's shared arena (published by whichever process built this
* directory's index first), so the worker materializes only the names it
* touches instead of the whole index.
*
* @param array<string, string> $classToFile
* @param array<string, array<int, string>> $functionToFiles
* @param array<string, string> $constantToFile
*/
public function __construct(
private FileNodesFetcher $fileNodesFetcher,
private Cache $cache,
private PhpVersion $phpVersion,
private FileContentHasher $fileContentHasher,
private array $classToFile,
private array $functionToFiles,
private array $constantToFile,
private ?string $arenaKeyPrefix = null,
private bool $awaitingBatchedScan = false,
)
{
}
/**
* Fills in the symbol maps of a locator created for a batched scan.
*
* The factory hands these out before the scan that produces their contents
* has run, so that one scan can cover every directory at once
* (see OptimizedDirectorySourceLocatorFactory::flushBatchedScan()). Nothing
* may look a symbol up in between - the maps are empty, so a lookup would
* quietly answer "not found" - which is what the flag guards.
*
* @param array<string, string> $classToFile
* @param array<string, array<int, string>> $functionToFiles
* @param array<string, string> $constantToFile
* @internal
*/
public function fillBatchedScan(array $classToFile, array $functionToFiles, array $constantToFile): void
{
$this->classToFile = $classToFile;
$this->functionToFiles = $functionToFiles;
$this->constantToFile = $constantToFile;
$this->awaitingBatchedScan = false;
}
/**
* @return array{non-empty-string, string}
*/
private function getCacheKeys(string $file, Identifier $identifier): array
{
$fileHash = $this->fileContentHasher->hash($file);
if ($fileHash === false) {
throw new CouldNotReadFileException($file);
}
$reflectionCacheKey = sprintf('odsl-%s-%s-%s', $file, $identifier->getType()->getName(), $identifier->getName());
$variableCacheKey = sprintf('v2-%s-%s-%s', ComposerHelper::getBetterReflectionVersion(), $this->phpVersion->getVersionString(), $fileHash);
return [$reflectionCacheKey, $variableCacheKey];
}
#[Override]
public function locateIdentifier(Reflector $reflector, Identifier $identifier): ?Reflection
{
if ($this->awaitingBatchedScan) {
throw new ShouldNotHappenException('Symbols were looked up in a directory whose batched scan has not been flushed yet.');
}
if ($identifier->isClass()) {
$identifierName = strtolower($identifier->getName());
$fileByClass = $this->findFileByClass($identifierName);
if ($fileByClass === null) {
return null;
}
$files = [$fileByClass];
} elseif ($identifier->isFunction()) {
$identifierName = strtolower($identifier->getName());
$files = $this->findFilesByFunction($identifierName);
} elseif ($identifier->isConstant()) {
$identifierName = ConstantNameHelper::normalize($identifier->getName());
$fileByConstant = $this->findFileByConstant($identifierName);
if ($fileByConstant === null) {
return null;
}
$files = [$fileByConstant];
} else {
return null;
}
foreach ($files as $oneFile) {
[$reflectionCacheKey, $variableCacheKey] = $this->getCacheKeys($oneFile, $identifier);
$cachedReflection = $this->cache->load($reflectionCacheKey, $variableCacheKey);
if ($cachedReflection === null) {
continue;
}
if ($identifier->isConstant()) {
return ReflectionConstant::importFromCache($reflector, $cachedReflection);
}
if ($identifier->isFunction()) {
return ReflectionFunction::importFromCache($reflector, $cachedReflection);
}
if ($identifier->isClass()) {
if (array_key_exists('backingType', $cachedReflection)) {
return ReflectionEnum::importFromCache($reflector, $cachedReflection);
}
return ReflectionClass::importFromCache($reflector, $cachedReflection);
}
}
if ($identifier->isClass()) {
$fetchedClassNode = null;
$fetchedFile = null;
foreach ($files as $file) {
$fetchedClassNodes = $this->fileNodesFetcher->fetchNodes($file)->getClassNodes();
if (!array_key_exists($identifierName, $fetchedClassNodes)) {
return null;
}
/** @var FetchedNode<Node\Stmt\ClassLike> $fetchedClassNode */
$fetchedClassNode = current($fetchedClassNodes[$identifierName]);
$fetchedFile = $file;
}
[$reflectionCacheKey, $variableCacheKey] = $this->getCacheKeys($fetchedFile, $identifier);
$classReflection = $this->nodeToReflection($reflector, $fetchedClassNode);
$this->cache->save($reflectionCacheKey, $variableCacheKey, $classReflection->exportToCache());
return $classReflection;
} elseif ($identifier->isFunction()) {
$fetchedFunctionNode = null;
foreach ($files as $file) {
$fetchedFunctionNodes = $this->fileNodesFetcher->fetchNodes($file)->getFunctionNodes();
if (!array_key_exists($identifierName, $fetchedFunctionNodes)) {
continue;
}
/** @var FetchedNode<Node\Stmt\Function_> $fetchedFunctionNode */
$fetchedFunctionNode = current($fetchedFunctionNodes[$identifierName]);
}
if ($fetchedFunctionNode === null) {
return null;
}
[$reflectionCacheKey, $variableCacheKey] = $this->getCacheKeys($file, $identifier);
$functionReflection = $this->nodeToReflection($reflector, $fetchedFunctionNode);
$this->cache->save($reflectionCacheKey, $variableCacheKey, $functionReflection->exportToCache());
return $functionReflection;
} elseif ($identifier->isConstant()) {
$fetchedConstantNode = null;
foreach ($files as $file) {
$fetchedConstantNodes = $this->fileNodesFetcher->fetchNodes($file)->getConstantNodes();
if (!array_key_exists($identifierName, $fetchedConstantNodes)) {
return null;
}
/** @var FetchedNode<Node\Stmt\Const_|Node\Expr\FuncCall> $fetchedConstantNode */
$fetchedConstantNode = current($fetchedConstantNodes[$identifierName]);
}
if ($fetchedConstantNode === null) {
return null;
}
[$reflectionCacheKey, $variableCacheKey] = $this->getCacheKeys($file, $identifier);
$constantReflection = $this->nodeToReflection(
$reflector,
$fetchedConstantNode,
$this->findConstantPositionInConstNode($fetchedConstantNode->getNode(), $identifierName),
);
$this->cache->save($reflectionCacheKey, $variableCacheKey, $constantReflection->exportToCache());
return $constantReflection;
}
return null;
}
/**
* @param FetchedNode<Node\Stmt\ClassLike>|FetchedNode<Node\Stmt\Function_>|FetchedNode<Node\Stmt\Const_|Node\Expr\FuncCall> $fetchedNode
*/
private function nodeToReflection(Reflector $reflector, FetchedNode $fetchedNode, ?int $positionInNode = null): ReflectionClass|ReflectionConstant|ReflectionFunction
{
$nodeToReflection = new NodeToReflection();
return $nodeToReflection->__invoke(
$reflector,
$fetchedNode->getNode(),
$fetchedNode->getLocatedSource(),
$fetchedNode->getNamespace(),
$positionInNode,
);
}
private function findFileByClass(string $className): ?string
{
if (array_key_exists($className, $this->classToFile)) {
return $this->classToFile[$className];
}
if ($this->arenaKeyPrefix === null) {
return null;
}
if (array_key_exists($className, $this->arenaClassLookups)) {
$file = $this->arenaClassLookups[$className];
} else {
$file = ArenaCache::lookupHash($this->arenaKeyPrefix . '-classes', $className);
if (!is_string($file)) {
$file = false;
}
$this->arenaClassLookups[$className] = $file;
}
return $file === false ? null : $file;
}
private function findFileByConstant(string $constantName): ?string
{
if (array_key_exists($constantName, $this->constantToFile)) {
return $this->constantToFile[$constantName];
}
if ($this->arenaKeyPrefix === null) {
return null;
}
if (array_key_exists($constantName, $this->arenaConstantLookups)) {
$file = $this->arenaConstantLookups[$constantName];
} else {
$file = ArenaCache::lookupHash($this->arenaKeyPrefix . '-constants', $constantName);
if (!is_string($file)) {
$file = false;
}
$this->arenaConstantLookups[$constantName] = $file;
}
return $file === false ? null : $file;
}
/**
* @return string[]
*/
private function findFilesByFunction(string $functionName): array
{
if (array_key_exists($functionName, $this->functionToFiles)) {
return $this->functionToFiles[$functionName];
}
if ($this->arenaKeyPrefix === null) {
return [];
}
if (array_key_exists($functionName, $this->arenaFunctionLookups)) {
$files = $this->arenaFunctionLookups[$functionName];
} else {
/** @var array<int, string>|mixed $files */
$files = ArenaCache::lookupHash($this->arenaKeyPrefix . '-functions', $functionName);
if (!is_array($files)) {
$files = false;
}
$this->arenaFunctionLookups[$functionName] = $files;
}
return $files === false ? [] : $files;
}
/**
* Enumeration needs the full maps: hydrates them from the arena records
* in their publication order, which equals the insertion order a locally
* built index would have. A null (a corrupt record — impossible with an
* intact arena, the factory gated on all three records) leaves a map
* empty rather than failing the run.
*/
private function hydrateSymbolsFromArena(): void
{
if ($this->arenaKeyPrefix === null || $this->hydratedFromArena) {
return;
}
$this->hydratedFromArena = true;
/** @var array<string, string>|null $classes */
$classes = ArenaCache::lookupHashAll($this->arenaKeyPrefix . '-classes');
if ($classes !== null) {
$this->classToFile = $classes;
}
/** @var array<string, array<int, string>>|null $functions */
$functions = ArenaCache::lookupHashAll($this->arenaKeyPrefix . '-functions');
if ($functions !== null) {
$this->functionToFiles = $functions;
}
/** @var array<string, string>|null $constants */
$constants = ArenaCache::lookupHashAll($this->arenaKeyPrefix . '-constants');
if ($constants === null) {
return;
}
$this->constantToFile = $constants;
}
/**
* @return list<Reflection>
*/
#[Override]
public function locateIdentifiersByType(Reflector $reflector, IdentifierType $identifierType): array
{
if ($this->awaitingBatchedScan) {
throw new ShouldNotHappenException('Symbols were looked up in a directory whose batched scan has not been flushed yet.');
}
$this->hydrateSymbolsFromArena();
$reflections = [];
if ($identifierType->isClass()) {
foreach ($this->classToFile as $file) {
$fetchedNodesResult = $this->fileNodesFetcher->fetchNodes($file);
foreach ($fetchedNodesResult->getClassNodes() as $identifierName => $fetchedClassNodes) {
foreach ($fetchedClassNodes as $fetchedClassNode) {
$reflections[$identifierName] = $this->nodeToReflection($reflector, $fetchedClassNode);
}
}
}
} elseif ($identifierType->isFunction()) {
foreach ($this->functionToFiles as $files) {
foreach ($files as $file) {
$fetchedNodesResult = $this->fileNodesFetcher->fetchNodes($file);
foreach ($fetchedNodesResult->getFunctionNodes() as $identifierName => $fetchedFunctionNodes) {
foreach ($fetchedFunctionNodes as $fetchedFunctionNode) {
$reflections[$identifierName] = $this->nodeToReflection($reflector, $fetchedFunctionNode);
continue 2;
}
}
}
}
} elseif ($identifierType->isConstant()) {
foreach ($this->constantToFile as $file) {
$fetchedNodesResult = $this->fileNodesFetcher->fetchNodes($file);
foreach ($fetchedNodesResult->getConstantNodes() as $identifierName => $fetchedConstantNodes) {
foreach ($fetchedConstantNodes as $fetchedConstantNode) {
$reflections[$identifierName] = $this->nodeToReflection(
$reflector,
$fetchedConstantNode,
$this->findConstantPositionInConstNode($fetchedConstantNode->getNode(), $identifierName),
);
}
}
}
}
return array_values($reflections);
}
private function findConstantPositionInConstNode(Node\Stmt\Const_|Node\Expr\FuncCall $constantNode, string $constantName): ?int
{
if ($constantNode instanceof Node\Expr\FuncCall) {
return null;
}
/** @var int $position */
foreach ($constantNode->consts as $position => $const) {
if ($const->namespacedName === null) {
throw new ShouldNotHappenException();
}
if (ConstantNameHelper::normalize($const->namespacedName->toString()) === $constantName) {
return $position;
}
}
throw new ShouldNotHappenException();
}
}