-
-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathNodeExpressionResolver.php
More file actions
721 lines (611 loc) · 24 KB
/
NodeExpressionResolver.php
File metadata and controls
721 lines (611 loc) · 24 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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
<?php
declare(strict_types=1);
/**
* Parser Reflection API
*
* @copyright Copyright 2015, Lisachenko Alexander <lisachenko.it@gmail.com>
*
* This source file is subject to the license that is bundled
* with this source code in the file LICENSE.
*/
namespace Go\ParserReflection\Resolver;
use Go\ParserReflection\ReflectionClass;
use Go\ParserReflection\ReflectionException;
use Go\ParserReflection\ReflectionFileNamespace;
use Go\ParserReflection\ReflectionNamedType;
use PhpParser\Node;
use PhpParser\Node\Const_;
use PhpParser\Node\Expr;
use PhpParser\Node\Name;
use PhpParser\Node\Param;
use PhpParser\Node\Scalar\Float_;
use PhpParser\Node\Scalar\Int_;
use PhpParser\Node\Scalar\MagicConst\Line;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt\Expression;
use PhpParser\PrettyPrinter\Standard;
use ReflectionFunctionAbstract;
use ReflectionMethod;
/**
* Tries to resolve expression into value
* @see \Go\ParserReflection\Resolver\NodeExpressionResolverTest
*/
class NodeExpressionResolver
{
/**
* List of exception for constant fetch
*/
private static array $notConstants = [
'true' => true,
'false' => true,
'null' => true,
];
/**
* Current reflection context for parsing
*/
private
\ReflectionClass|\ReflectionFunction|\ReflectionMethod|\ReflectionClassConstant|
\ReflectionParameter|\ReflectionAttribute|\ReflectionProperty|ReflectionFileNamespace|null $context;
/**
* Flag if given expression is constant
*/
private bool $isConstant = false;
/**
* If given expression is constant-like (used mostly for dumping string representation) of node in reflection
*/
private bool $isConstExpr = false;
/**
* Name of the constant (if present), used to collect references to constants for misc places
* @see $isConstant
*/
private ?string $constantName;
/**
* Node resolving level, 1 = top-level
*/
private int $nodeLevel = 0;
/**
* @var Node[]
*/
private array $nodeStack = [];
private mixed $value;
public function __construct($context)
{
$this->context = $context;
}
public function getConstantName(): ?string
{
return $this->constantName;
}
public function getValue(): mixed
{
return $this->value;
}
public function isConstant(): bool
{
return $this->isConstant;
}
public function isConstExpression(): bool
{
return $this->isConstExpr;
}
public function getConstExpression(): ?string
{
$expression = null;
if ($this->isConstExpr) {
// Clone node to avoid possible side-effects
$node = clone $this->nodeStack[$this->nodeLevel];
if ($node instanceof Expr\ConstFetch) {
$constantNodeName = $node->name;
// Unpack fully-resolved name if we have it inside attribute
if ($constantNodeName->hasAttribute('resolvedName')) {
$constantNodeName = $constantNodeName->getAttribute('resolvedName');
}
if ($constantNodeName->isFullyQualified()) {
// For full-qualified names we would like to remove leading "\"
$node->name = new Name(ltrim($constantNodeName->toString(), '\\'));
} else {
// For relative names we would like to add namespace prefix
$node->name = new Name($this->resolveScalarMagicConstNamespace() . '\\' . $constantNodeName->toString());
}
}
// All long array nodes are pretty-printed by PHP in short format
if ($node instanceof Expr\Array_ && $node->getAttribute('kind') === Expr\Array_::KIND_LONG) {
$node->setAttribute('kind', Expr\Array_::KIND_SHORT);
}
$printer = new Standard(['shortArraySyntax' => true]);
$expression = $printer->prettyPrintExpr($node);
}
return $expression;
}
/**
* @throws ReflectionException If node could not be resolved
*/
final public function process(Node $node): void
{
$this->nodeLevel = 0;
$this->nodeStack = [$node]; // Always keep the root node
$this->isConstant = false;
$this->isConstExpr = false;
$this->constantName = null;
$this->value = $this->resolve($node);
}
/**
* Recursively resolves node into valid value
*
* @throws ReflectionException If couldn't resolve value for given Node
*/
final protected function resolve(Node $node): mixed
{
$value = null;
try {
$this->nodeStack[] = $node;
++$this->nodeLevel;
if ($this->nodeLevel > 1 && $this->isConstant) {
$this->isConstant = false;
$this->constantName = null;
}
$methodName = $this->getDispatchMethodFor($node);
if (!method_exists($this, $methodName)) {
throw new ReflectionException("Could not find handler for the " . __CLASS__ . "::{$methodName} method");
}
$value = $this->$methodName($node);
} finally {
array_pop($this->nodeStack);
--$this->nodeLevel;
}
return $value;
}
protected function resolveStmtExpression(Expression $node): mixed
{
// Just unwrap "expr;" statements.
return $this->resolve($node->expr);
}
protected function resolveNameFullyQualified(Name\FullyQualified $node): string
{
return $node->toString();
}
private function resolveName(Name $node): string
{
if ($node->hasAttribute('resolvedName')) {
return $node->getAttribute('resolvedName')->toString();
}
return $node->toString();
}
protected function resolveIdentifier(Node\Identifier $node): string
{
return $node->toString();
}
/**
* @throws \Throwable In case of any errors during function evaluation
*/
protected function resolveExprFuncCall(Expr\FuncCall $node): mixed
{
$functionName = $this->resolve($node->name);
$resolvedArgs = [];
foreach ($node->args as $argumentNode) {
$value = $this->resolve($argumentNode->value);
// if function uses named arguments, then unpack argument name first
if (isset($argumentNode->name)) {
$name = $this->resolve($argumentNode->name);
$resolvedArgs[$name] = $value;
} else {
// otherwise simply add argument to the list
$resolvedArgs[] = $value;
}
}
$reflectedFunction = new \ReflectionFunction($functionName);
if (!$reflectedFunction->isInternal()) {
throw new ReflectionException("Only internal PHP functions can be evaluated safely");
}
return $reflectedFunction->invoke(...$resolvedArgs);
}
/**
* Resolves new expression by instantiating the class with constructor arguments
*
* @throws \Throwable In case of any errors during class instantiation
*/
protected function resolveExprNew(Expr\New_ $node): object
{
$classToInstantiateNode = $node->class;
// Resolve class name - it can be a Name node or an expression
if ($classToInstantiateNode instanceof Node\Name) {
// Unwrap resolved class name if we have it inside attributes
if ($classToInstantiateNode->hasAttribute('resolvedName')) {
$classToInstantiateNode = $classToInstantiateNode->getAttribute('resolvedName');
}
$className = $classToInstantiateNode->toString();
} else {
// It's an expression, resolve it to get class name
$className = $this->resolve($classToInstantiateNode);
if (!is_string($className)) {
throw new ReflectionException("Unable to resolve class name for instantiation.");
}
}
// Resolve constructor arguments
$resolvedArgs = [];
foreach ($node->args as $argumentNode) {
$value = $this->resolve($argumentNode->value);
// if constructor uses named arguments, then unpack argument name first
if (isset($argumentNode->name)) {
$name = $this->resolve($argumentNode->name);
$resolvedArgs[$name] = $value;
} else {
// otherwise simply add argument to the list
$resolvedArgs[] = $value;
}
}
// Use ReflectionClass to safely instantiate the class
$reflectionClass = new \ReflectionClass($className);
return $reflectionClass->newInstance(...$resolvedArgs);
}
protected function resolveScalarFloat(Float_ $node): float
{
return $node->value;
}
protected function resolveScalarInt(Int_ $node): int
{
return $node->value;
}
protected function resolveScalarString(String_ $node): string
{
return $node->value;
}
/**
* @throws ReflectionException If not in the context of parsing method body
*/
protected function resolveScalarMagicConstMethod(): string
{
if (!$this->context instanceof ReflectionMethod) {
throw new ReflectionException("Could not resolve __METHOD__ without method context");
}
return $this->context->getDeclaringClass()->name . '::' . $this->context->getShortName();
}
/**
* @throws ReflectionException If not in the context of parsing function body
*/
protected function resolveScalarMagicConstFunction(): string
{
if (!$this->context instanceof ReflectionFunctionAbstract) {
throw new ReflectionException("Could not resolve __FUNCTION__ without function context");
}
return $this->context->getName();
}
/**
* @throws ReflectionException If not inside ReflectionFileNamespace or context doesn't have getNamespaceName()
*/
protected function resolveScalarMagicConstNamespace(): string
{
if ($this->context instanceof ReflectionFileNamespace) {
return $this->context->getName();
}
if (!method_exists($this->context, 'getNamespaceName')) {
throw new ReflectionException("Could not resolve __NAMESPACE__ without having getNamespaceName");
}
return $this->context->getNamespaceName();
}
/**
* @throws ReflectionException If not inside ReflectionClass or class children nodes
*/
protected function resolveScalarMagicConstClass(): string
{
if ($this->context instanceof \ReflectionClass) {
return $this->context->name;
}
if (!method_exists($this->context, 'getDeclaringClass')) {
throw new ReflectionException("Could not resolve __CLASS__ without having getDeclaringClass");
}
$declaringClass = $this->context->getDeclaringClass();
return $declaringClass->name;
}
/**
* @throws ReflectionException If ReflectionContext doesn't have getFileName
*/
protected function resolveScalarMagicConstDir(): string
{
if (!method_exists($this->context, 'getFileName')) {
throw new ReflectionException("Could not resolve __DIR__ without having getFileName");
}
return dirname($this->context->getFileName());
}
/**
* @throws ReflectionException If ReflectionContext doesn't have getFileName
*/
protected function resolveScalarMagicConstFile(): string
{
if (!method_exists($this->context, 'getFileName')) {
throw new ReflectionException("Could not resolve __FILE__ without having getFileName");
}
return $this->context->getFileName();
}
protected function resolveScalarMagicConstLine(Line $node): int
{
return $node->getStartLine();
}
/**
* @throws ReflectionException If not inside trait context
*/
protected function resolveScalarMagicConstTrait(): string
{
if (!$this->context instanceof \ReflectionClass || !$this->context->isTrait()) {
throw new ReflectionException("Could not resolve __TRAIT__ without trait context");
}
return $this->context->name;
}
protected function resolveExprConstFetch(Expr\ConstFetch $node)
{
$constantValue = null;
$isResolved = false;
$nodeConstantName = $node->name;
// If we have resolved type name
if ($nodeConstantName->hasAttribute('resolvedName')) {
$nodeConstantName = $nodeConstantName->getAttribute('resolvedName');
}
$isFQNConstant = $nodeConstantName instanceof Node\Name\FullyQualified;
$constantName = $nodeConstantName->toString();
if (!$isFQNConstant && method_exists($this->context, 'getFileName')) {
$fileName = $this->context->getFileName();
$namespaceName = $this->resolveScalarMagicConstNamespace();
$fileNamespace = new ReflectionFileNamespace($fileName, $namespaceName);
if ($fileNamespace->hasConstant($constantName)) {
$constantValue = $fileNamespace->getConstant($constantName);
$constantName = $fileNamespace->getName() . '\\' . $constantName;
$isResolved = true;
}
}
$isRealConstant = !isset(self::$notConstants[$constantName]);
if (!$isResolved && defined($constantName)) {
$constantValue = constant($constantName);
if (!$isFQNConstant) {
$constantName = $this->context->getNamespaceName() . '\\' . $constantName;
}
}
if ($this->nodeLevel === 1 && $isRealConstant) {
$this->isConstant = true;
$this->isConstExpr = true;
$this->constantName = $constantName;
}
return $constantValue;
}
protected function resolveExprClassConstFetch(Expr\ClassConstFetch $node)
{
$classToReflectNodeName = $node->class;
if (!($classToReflectNodeName instanceof Node\Name)) {
$classToReflectNodeName = $this->resolve($classToReflectNodeName);
if (!is_string($classToReflectNodeName)) {
throw new ReflectionException("Unable to resolve class constant.");
}
// Strings evaluated as class names are always treated as fully
// qualified.
$classToReflectNodeName = new Node\Name\FullyQualified(ltrim($classToReflectNodeName, '\\'));
}
// Unwrap resolved class name if we have it inside attributes
if ($classToReflectNodeName->hasAttribute('resolvedName')) {
$classToReflectNodeName = $classToReflectNodeName->getAttribute('resolvedName');
}
$refClass = $this->fetchReflectionClass($classToReflectNodeName);
if (($node->name instanceof Expr\Error)) {
$constantName = '';
} else {
$constantName = match (true) {
$node->name->hasAttribute('resolvedName') => $node->name->getAttribute('resolvedName')->toString(),
default => $node->name->toString(),
};
}
// special handling of ::class constants
if ('class' === $constantName) {
return $refClass->getName();
}
$this->isConstant = true;
$this->isConstExpr = true;
$this->constantName = $classToReflectNodeName . '::' . $constantName;
return $refClass->getConstant($constantName);
}
protected function resolveExprArray(Expr\Array_ $node): array
{
// For array expressions we would like to have pretty-printed output too
$this->isConstExpr = true;
$result = [];
foreach ($node->items as $itemIndex => $arrayItem) {
$itemValue = $this->resolve($arrayItem->value);
$itemKey = isset($arrayItem->key) ? $this->resolve($arrayItem->key) : $itemIndex;
$result[$itemKey] = $itemValue;
}
return $result;
}
protected function resolveExprBinaryOpPlus(Expr\BinaryOp\Plus $node): int|float|array
{
return $this->resolve($node->left) + $this->resolve($node->right);
}
protected function resolveExprBinaryOpMinus(Expr\BinaryOp\Minus $node): int|float
{
return $this->resolve($node->left) - $this->resolve($node->right);
}
protected function resolveExprBinaryOpMul(Expr\BinaryOp\Mul $node): int|float
{
return $this->resolve($node->left) * $this->resolve($node->right);
}
protected function resolveExprBinaryOpPow(Expr\BinaryOp\Pow $node): int|float
{
return $this->resolve($node->left) ** $this->resolve($node->right);
}
protected function resolveExprBinaryOpDiv(Expr\BinaryOp\Div $node): int|float
{
return $this->resolve($node->left) / $this->resolve($node->right);
}
/**
* Operands of modulo are converted to int before processing
*
* @see https://www.php.net/manual/en/language.operators.arithmetic.php#language.operators.arithmetic
*/
protected function resolveExprBinaryOpMod(Expr\BinaryOp\Mod $node): int
{
return $this->resolve($node->left) % $this->resolve($node->right);
}
protected function resolveExprBooleanNot(Expr\BooleanNot $node): bool
{
return !$this->resolve($node->expr);
}
protected function resolveExprBitwiseNot(Expr\BitwiseNot $node): int|string
{
return ~$this->resolve($node->expr);
}
protected function resolveExprBinaryOpBitwiseOr(Expr\BinaryOp\BitwiseOr $node): int
{
return $this->resolve($node->left) | $this->resolve($node->right);
}
protected function resolveExprBinaryOpBitwiseAnd(Expr\BinaryOp\BitwiseAnd $node): int
{
return $this->resolve($node->left) & $this->resolve($node->right);
}
protected function resolveExprBinaryOpBitwiseXor(Expr\BinaryOp\BitwiseXor $node): int
{
return $this->resolve($node->left) ^ $this->resolve($node->right);
}
protected function resolveExprBinaryOpShiftLeft(Expr\BinaryOp\ShiftLeft $node): int
{
return $this->resolve($node->left) << $this->resolve($node->right);
}
protected function resolveExprBinaryOpShiftRight(Expr\BinaryOp\ShiftRight $node): int
{
return $this->resolve($node->left) >> $this->resolve($node->right);
}
protected function resolveExprBinaryOpConcat(Expr\BinaryOp\Concat $node): string
{
return $this->resolve($node->left) . $this->resolve($node->right);
}
protected function resolveExprTernary(Expr\Ternary $node): mixed
{
if (isset($node->if)) {
// Full syntax $a ? $b : $c;
return $this->resolve($node->cond) ? $this->resolve($node->if) : $this->resolve($node->else);
}
return $this->resolve($node->cond) ?: $this->resolve($node->else);
}
protected function resolveExprBinaryOpSmallerOrEqual(Expr\BinaryOp\SmallerOrEqual $node): bool
{
return $this->resolve($node->left) <= $this->resolve($node->right);
}
protected function resolveExprBinaryOpGreaterOrEqual(Expr\BinaryOp\GreaterOrEqual $node): bool
{
return $this->resolve($node->left) >= $this->resolve($node->right);
}
protected function resolveExprBinaryOpEqual(Expr\BinaryOp\Equal $node): bool
{
/** @noinspection TypeUnsafeComparisonInspection */
return $this->resolve($node->left) == $this->resolve($node->right);
}
protected function resolveExprBinaryOpNotEqual(Expr\BinaryOp\NotEqual $node): bool
{
/** @noinspection TypeUnsafeComparisonInspection */
return $this->resolve($node->left) != $this->resolve($node->right);
}
protected function resolveExprBinaryOpSmaller(Expr\BinaryOp\Smaller $node): bool
{
return $this->resolve($node->left) < $this->resolve($node->right);
}
protected function resolveExprBinaryOpGreater(Expr\BinaryOp\Greater $node): bool
{
return $this->resolve($node->left) > $this->resolve($node->right);
}
protected function resolveExprBinaryOpIdentical(Expr\BinaryOp\Identical $node): bool
{
return $this->resolve($node->left) === $this->resolve($node->right);
}
protected function resolveExprBinaryOpNotIdentical(Expr\BinaryOp\NotIdentical $node): bool
{
return $this->resolve($node->left) !== $this->resolve($node->right);
}
protected function resolveExprBinaryOpBooleanAnd(Expr\BinaryOp\BooleanAnd $node): bool
{
return $this->resolve($node->left) && $this->resolve($node->right);
}
protected function resolveExprBinaryOpLogicalAnd(Expr\BinaryOp\LogicalAnd $node): bool
{
return $this->resolve($node->left) and $this->resolve($node->right);
}
protected function resolveExprBinaryOpBooleanOr(Expr\BinaryOp\BooleanOr $node): bool
{
return $this->resolve($node->left) || $this->resolve($node->right);
}
protected function resolveExprBinaryOpLogicalOr(Expr\BinaryOp\LogicalOr $node): bool
{
return $this->resolve($node->left) or $this->resolve($node->right);
}
protected function resolveExprBinaryOpLogicalXor(Expr\BinaryOp\LogicalXor $node): bool
{
return $this->resolve($node->left) xor $this->resolve($node->right);
}
protected function resolveExprUnaryMinus(Expr\UnaryMinus $node): int|float
{
return -$this->resolve($node->expr);
}
protected function resolveExprUnaryPlus(Expr\UnaryPlus $node): int|float
{
return $this->resolve($node->expr);
}
private function getDispatchMethodFor(Node $node): string
{
$nodeType = $node->getType();
return 'resolve' . str_replace('_', '', $nodeType);
}
/**
* Utility method to fetch reflection class instance by name
*
* Supports:
* 'self' keyword
* 'parent' keyword
* not-FQN class names
*
* @param Node\Name $node Class name node
*
* @return bool|\ReflectionClass
*
* @throws ReflectionException
*/
private function fetchReflectionClass(Node\Name $node)
{
// If we have already resolved node name, we should use it instead
if ($node->hasAttribute('resolvedName')) {
$node = $node->getAttribute('resolvedName');
}
$className = $node->toString();
$isFQNClass = $node instanceof Node\Name\FullyQualified;
if ($isFQNClass) {
// check to see if the class is already loaded and is safe to use
// PHP's ReflectionClass to determine if the class is user defined
if (class_exists($className, false)) {
$refClass = new \ReflectionClass($className);
if (!$refClass->isUserDefined()) {
return $refClass;
}
}
return new ReflectionClass($className);
}
if ('self' === $className) {
if ($this->context instanceof \ReflectionClass) {
return $this->context;
}
if (method_exists($this->context, 'getDeclaringClass')) {
return $this->context->getDeclaringClass();
}
}
if ('parent' === $className) {
if ($this->context instanceof \ReflectionClass) {
return $this->context->getParentClass();
}
if (method_exists($this->context, 'getDeclaringClass')) {
return $this->context->getDeclaringClass()
->getParentClass()
;
}
}
if (method_exists($this->context, 'getFileName')) {
/** @var ReflectionFileNamespace|null $fileNamespace */
$fileName = $this->context->getFileName();
$namespaceName = $this->resolveScalarMagicConstNamespace();
$fileNamespace = new ReflectionFileNamespace($fileName, $namespaceName);
return $fileNamespace->getClass($className);
}
throw new ReflectionException("Can not resolve class $className");
}
}