-
-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathNameResolver.php
More file actions
440 lines (375 loc) · 15.1 KB
/
NameResolver.php
File metadata and controls
440 lines (375 loc) · 15.1 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
431
432
433
434
435
436
437
438
439
440
<?php
declare(strict_types=1);
namespace Arkitect\Analyzer;
use PhpParser\Comment\Doc;
use PhpParser\ErrorHandler;
use PhpParser\NameContext;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Name;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Use_;
use PhpParser\NodeAbstract;
use PhpParser\NodeVisitorAbstract;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode;
use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode;
use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
use PHPStan\PhpDocParser\Lexer\Lexer;
use PHPStan\PhpDocParser\Parser\ConstExprParser;
use PHPStan\PhpDocParser\Parser\PhpDocParser;
use PHPStan\PhpDocParser\Parser\TokenIterator;
use PHPStan\PhpDocParser\Parser\TypeParser;
class NameResolver extends NodeVisitorAbstract
{
/** @var NameContext Naming context */
protected $nameContext;
/** @var bool Whether to preserve original names */
protected $preserveOriginalNames;
/** @var bool Whether to replace resolved nodes in place, or to add resolvedNode attributes */
protected $replaceNodes;
/** @var bool Whether to parse DocBlock Custom Annotations */
protected $parseCustomAnnotations;
/** @var PhpDocParser */
protected $phpDocParser;
/** @var Lexer */
protected $phpDocLexer;
/**
* Constructs a name resolution visitor.
*
* Options:
* * preserveOriginalNames (default false): An "originalName" attribute will be added to
* all name nodes that underwent resolution.
* * replaceNodes (default true): Resolved names are replaced in-place. Otherwise, a
* resolvedName attribute is added. (Names that cannot be statically resolved receive a
* namespacedName attribute, as usual.)
* * parseCustomAnnotations (default true): Whether to parse DocBlock Custom Annotations.
*
* @param ErrorHandler|null $errorHandler Error handler
* @param array $options Options
*/
public function __construct(ErrorHandler $errorHandler = null, array $options = [])
{
$this->nameContext = new NameContext($errorHandler ?? new ErrorHandler\Throwing());
$this->preserveOriginalNames = $options['preserveOriginalNames'] ?? false;
$this->replaceNodes = $options['replaceNodes'] ?? true;
$this->parseCustomAnnotations = $options['parseCustomAnnotations'] ?? true;
$typeParser = new TypeParser();
$constExprParser = new ConstExprParser();
$this->phpDocParser = new PhpDocParser($typeParser, $constExprParser);
$this->phpDocLexer = new Lexer();
}
/**
* Get name resolution context.
*/
public function getNameContext(): NameContext
{
return $this->nameContext;
}
public function beforeTraverse(array $nodes)
{
$this->nameContext->startNamespace();
return null;
}
public function enterNode(Node $node)
{
if ($node instanceof Stmt\Namespace_) {
$this->nameContext->startNamespace($node->name);
} elseif ($node instanceof Stmt\Use_) {
foreach ($node->uses as $use) {
$this->addAlias($use, $node->type, null);
}
} elseif ($node instanceof Stmt\GroupUse) {
foreach ($node->uses as $use) {
$this->addAlias($use, $node->type, $node->prefix);
}
} elseif ($node instanceof Stmt\Class_) {
if (null !== $node->extends) {
$node->extends = $this->resolveClassName($node->extends);
}
foreach ($node->implements as &$interface) {
$interface = $this->resolveClassName($interface);
}
$this->resolveAttrGroups($node);
if (null !== $node->name) {
$this->addNamespacedName($node);
}
} elseif ($node instanceof Stmt\Interface_) {
foreach ($node->extends as &$interface) {
$interface = $this->resolveClassName($interface);
}
$this->resolveAttrGroups($node);
$this->addNamespacedName($node);
} elseif ($node instanceof Stmt\Enum_) {
foreach ($node->implements as &$interface) {
$interface = $this->resolveClassName($interface);
}
$this->resolveAttrGroups($node);
if (null !== $node->name) {
$this->addNamespacedName($node);
}
} elseif ($node instanceof Stmt\Trait_) {
$this->resolveAttrGroups($node);
$this->addNamespacedName($node);
} elseif ($node instanceof Stmt\Function_) {
$this->resolveSignature($node);
$this->resolveAttrGroups($node);
$this->addNamespacedName($node);
} elseif ($node instanceof Stmt\ClassMethod
|| $node instanceof Expr\Closure
|| $node instanceof Expr\ArrowFunction
) {
$this->resolveSignature($node);
$this->resolveAttrGroups($node);
} elseif ($node instanceof Stmt\Property) {
if (null !== $node->type) {
$node->type = $this->resolveType($node->type);
}
$this->resolveAttrGroups($node);
$phpDocNode = $this->getPhpDocNode($node);
if (null === $phpDocNode) {
return;
}
if ($this->isNodeOfTypeArray($node)) {
$arrayItemType = null;
foreach ($phpDocNode->getVarTagValues() as $tagValue) {
$arrayItemType = $this->getArrayItemType($tagValue->type);
}
if (null !== $arrayItemType) {
$node->type = $this->resolveName(new Node\Name($arrayItemType), Use_::TYPE_NORMAL);
return;
}
}
foreach ($phpDocNode->getVarTagValues() as $tagValue) {
$type = $this->resolveName(new Node\Name((string) $tagValue->type), Use_::TYPE_NORMAL);
$node->type = $type;
break;
}
if ($this->parseCustomAnnotations && !($node->type instanceof FullyQualified)) {
foreach ($phpDocNode->getTags() as $tagValue) {
if ('@' === $tagValue->name[0] && !str_contains($tagValue->name, '@var')) {
$customTag = str_replace('@', '', $tagValue->name);
$type = $this->resolveName(new Node\Name($customTag), Use_::TYPE_NORMAL);
$node->type = $type;
break;
}
}
}
} elseif ($node instanceof Stmt\Const_) {
foreach ($node->consts as $const) {
$this->addNamespacedName($const);
}
} elseif ($node instanceof Stmt\ClassConst) {
$this->resolveAttrGroups($node);
} elseif ($node instanceof Stmt\EnumCase) {
$this->resolveAttrGroups($node);
} elseif ($node instanceof Expr\StaticCall
|| $node instanceof Expr\StaticPropertyFetch
|| $node instanceof Expr\ClassConstFetch
|| $node instanceof Expr\New_
|| $node instanceof Expr\Instanceof_
) {
if ($node->class instanceof Name) {
$node->class = $this->resolveClassName($node->class);
}
} elseif ($node instanceof Stmt\Catch_) {
foreach ($node->types as &$type) {
$type = $this->resolveClassName($type);
}
} elseif ($node instanceof Expr\FuncCall) {
if ($node->name instanceof Name) {
$node->name = $this->resolveName($node->name, Stmt\Use_::TYPE_FUNCTION);
}
} elseif ($node instanceof Expr\ConstFetch) {
$node->name = $this->resolveName($node->name, Stmt\Use_::TYPE_CONSTANT);
} elseif ($node instanceof Stmt\TraitUse) {
foreach ($node->traits as &$trait) {
$trait = $this->resolveClassName($trait);
}
foreach ($node->adaptations as $adaptation) {
if (null !== $adaptation->trait) {
$adaptation->trait = $this->resolveClassName($adaptation->trait);
}
if ($adaptation instanceof Stmt\TraitUseAdaptation\Precedence) {
foreach ($adaptation->insteadof as &$insteadof) {
$insteadof = $this->resolveClassName($insteadof);
}
}
}
}
return null;
}
/**
* Resolve name, according to name resolver options.
*
* @param Name $name Function or constant name to resolve
* @param int $type One of Stmt\Use_::TYPE_*
*
* @return Name Resolved name, or original name with attribute
*/
protected function resolveName(Name $name, int $type): Name
{
if (!$this->replaceNodes) {
$resolvedName = $this->nameContext->getResolvedName($name, $type);
if (null !== $resolvedName) {
$name->setAttribute('resolvedName', $resolvedName);
} else {
$name->setAttribute('namespacedName', FullyQualified::concat(
$this->nameContext->getNamespace(),
$name,
$name->getAttributes()
));
}
return $name;
}
if ($this->preserveOriginalNames) {
// Save the original name
$originalName = $name;
$name = clone $originalName;
$name->setAttribute('originalName', $originalName);
}
$resolvedName = $this->nameContext->getResolvedName($name, $type);
if (null !== $resolvedName) {
return $resolvedName;
}
// unqualified names inside a namespace cannot be resolved at compile-time
// add the namespaced version of the name as an attribute
$name->setAttribute('namespacedName', FullyQualified::concat(
$this->nameContext->getNamespace(),
$name,
$name->getAttributes()
));
return $name;
}
protected function resolveClassName(Name $name): Name
{
return $this->resolveName($name, Stmt\Use_::TYPE_NORMAL);
}
/**
* @psalm-suppress NoInterfaceProperties
*/
protected function addNamespacedName(Node $node): void
{
$node->namespacedName = Name::concat(
$this->nameContext->getNamespace(),
(string) $node->name
);
}
/**
* @psalm-suppress NoInterfaceProperties
*/
protected function resolveAttrGroups(Node $node): void
{
foreach ($node->attrGroups as $attrGroup) {
foreach ($attrGroup->attrs as $attr) {
$attr->name = $this->resolveClassName($attr->name);
}
}
}
private function addAlias(Stmt\UseUse $use, int $type, Name $prefix = null): void
{
// Add prefix for group uses
/** @var Name $name */
$name = $prefix ? Name::concat($prefix, $use->name) : $use->name;
// Type is determined either by individual element or whole use declaration
$type |= $use->type;
$this->nameContext->addAlias(
$name,
(string) $use->getAlias(),
$type,
$use->getAttributes()
);
}
/** @param Stmt\Function_|Stmt\ClassMethod|Expr\Closure|Expr\ArrowFunction $node */
private function resolveSignature($node): void
{
$phpDocNode = $this->getPhpDocNode($node);
foreach ($node->params as $param) {
$param->type = $this->resolveType($param->type);
$this->resolveAttrGroups($param);
if ($this->isNodeOfTypeArray($param) && null !== $phpDocNode) {
foreach ($phpDocNode->getParamTagValues() as $phpDocParam) {
if ($param->var instanceof Expr\Variable && \is_string($param->var->name) && $phpDocParam->parameterName === ('$'.$param->var->name)) {
$arrayItemType = $this->getArrayItemType($phpDocParam->type);
if (null !== $arrayItemType) {
$param->type = $this->resolveName(new Node\Name($arrayItemType), Use_::TYPE_NORMAL);
}
}
}
}
}
$node->returnType = $this->resolveType($node->returnType);
if ($node->returnType instanceof Node\Identifier && 'array' === $node->returnType->name && null !== $phpDocNode) {
$arrayItemType = null;
foreach ($phpDocNode->getReturnTagValues() as $tagValue) {
$arrayItemType = $this->getArrayItemType($tagValue->type);
}
if (null !== $arrayItemType) {
$node->returnType = $this->resolveName(new Node\Name($arrayItemType), Use_::TYPE_NORMAL);
}
}
}
/**
* @psalm-suppress MissingParamType
* @psalm-suppress PossiblyNullArgument
* @psalm-suppress MissingReturnType
*/
private function resolveType($node)
{
if ($node instanceof Name) {
return $this->resolveClassName($node);
}
if ($node instanceof Node\NullableType) {
$node->type = $this->resolveType($node->type);
return $node;
}
if ($node instanceof Node\UnionType || $node instanceof Node\IntersectionType) {
foreach ($node->types as &$type) {
$type = $this->resolveType($type);
}
return $node;
}
return $node;
}
private function getPhpDocNode(NodeAbstract $node): ?PhpDocNode
{
if (null === $node->getDocComment()) {
return null;
}
/** @var Doc $docComment */
$docComment = $node->getDocComment();
$tokens = $this->phpDocLexer->tokenize($docComment->getText());
$tokenIterator = new TokenIterator($tokens);
return $this->phpDocParser->parse($tokenIterator);
}
/**
* @param Node\Param|Stmt\Property $node
*/
private function isNodeOfTypeArray($node): bool
{
return null !== $node->type && isset($node->type->name) && 'array' === $node->type->name;
}
private function getArrayItemType(TypeNode $typeNode): ?string
{
$arrayItemType = null;
if ($typeNode instanceof GenericTypeNode) {
if (1 === \count($typeNode->genericTypes)) {
// this handles list<ClassName>
$arrayItemType = (string) $typeNode->genericTypes[0];
} elseif (2 === \count($typeNode->genericTypes)) {
// this handles array<int, ClassName>
$arrayItemType = (string) $typeNode->genericTypes[1];
}
}
if ($typeNode instanceof ArrayTypeNode) {
// this handles ClassName[]
$arrayItemType = (string) $typeNode->type;
}
$validFqcn = '/^[a-zA-Z_\x7f-\xff\\\\][a-zA-Z0-9_\x7f-\xff\\\\]*[a-zA-Z0-9_\x7f-\xff]$/';
if (null !== $arrayItemType && !(bool) preg_match($validFqcn, $arrayItemType)) {
return null;
}
return $arrayItemType;
}
}