You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

226 lines
8.9 KiB

3 years ago
  1. <?php
  2. namespace PhpParser;
  3. use PhpParser\Node\Expr;
  4. use PhpParser\Node\Scalar;
  5. /**
  6. * Evaluates constant expressions.
  7. *
  8. * This evaluator is able to evaluate all constant expressions (as defined by PHP), which can be
  9. * evaluated without further context. If a subexpression is not of this type, a user-provided
  10. * fallback evaluator is invoked. To support all constant expressions that are also supported by
  11. * PHP (and not already handled by this class), the fallback evaluator must be able to handle the
  12. * following node types:
  13. *
  14. * * All Scalar\MagicConst\* nodes.
  15. * * Expr\ConstFetch nodes. Only null/false/true are already handled by this class.
  16. * * Expr\ClassConstFetch nodes.
  17. *
  18. * The fallback evaluator should throw ConstExprEvaluationException for nodes it cannot evaluate.
  19. *
  20. * The evaluation is dependent on runtime configuration in two respects: Firstly, floating
  21. * point to string conversions are affected by the precision ini setting. Secondly, they are also
  22. * affected by the LC_NUMERIC locale.
  23. */
  24. class ConstExprEvaluator
  25. {
  26. private $fallbackEvaluator;
  27. /**
  28. * Create a constant expression evaluator.
  29. *
  30. * The provided fallback evaluator is invoked whenever a subexpression cannot be evaluated. See
  31. * class doc comment for more information.
  32. *
  33. * @param callable|null $fallbackEvaluator To call if subexpression cannot be evaluated
  34. */
  35. public function __construct(callable $fallbackEvaluator = null) {
  36. $this->fallbackEvaluator = $fallbackEvaluator ?? function(Expr $expr) {
  37. throw new ConstExprEvaluationException(
  38. "Expression of type {$expr->getType()} cannot be evaluated"
  39. );
  40. };
  41. }
  42. /**
  43. * Silently evaluates a constant expression into a PHP value.
  44. *
  45. * Thrown Errors, warnings or notices will be converted into a ConstExprEvaluationException.
  46. * The original source of the exception is available through getPrevious().
  47. *
  48. * If some part of the expression cannot be evaluated, the fallback evaluator passed to the
  49. * constructor will be invoked. By default, if no fallback is provided, an exception of type
  50. * ConstExprEvaluationException is thrown.
  51. *
  52. * See class doc comment for caveats and limitations.
  53. *
  54. * @param Expr $expr Constant expression to evaluate
  55. * @return mixed Result of evaluation
  56. *
  57. * @throws ConstExprEvaluationException if the expression cannot be evaluated or an error occurred
  58. */
  59. public function evaluateSilently(Expr $expr) {
  60. set_error_handler(function($num, $str, $file, $line) {
  61. throw new \ErrorException($str, 0, $num, $file, $line);
  62. });
  63. try {
  64. return $this->evaluate($expr);
  65. } catch (\Throwable $e) {
  66. if (!$e instanceof ConstExprEvaluationException) {
  67. $e = new ConstExprEvaluationException(
  68. "An error occurred during constant expression evaluation", 0, $e);
  69. }
  70. throw $e;
  71. } finally {
  72. restore_error_handler();
  73. }
  74. }
  75. /**
  76. * Directly evaluates a constant expression into a PHP value.
  77. *
  78. * May generate Error exceptions, warnings or notices. Use evaluateSilently() to convert these
  79. * into a ConstExprEvaluationException.
  80. *
  81. * If some part of the expression cannot be evaluated, the fallback evaluator passed to the
  82. * constructor will be invoked. By default, if no fallback is provided, an exception of type
  83. * ConstExprEvaluationException is thrown.
  84. *
  85. * See class doc comment for caveats and limitations.
  86. *
  87. * @param Expr $expr Constant expression to evaluate
  88. * @return mixed Result of evaluation
  89. *
  90. * @throws ConstExprEvaluationException if the expression cannot be evaluated
  91. */
  92. public function evaluateDirectly(Expr $expr) {
  93. return $this->evaluate($expr);
  94. }
  95. private function evaluate(Expr $expr) {
  96. if ($expr instanceof Scalar\LNumber
  97. || $expr instanceof Scalar\DNumber
  98. || $expr instanceof Scalar\String_
  99. ) {
  100. return $expr->value;
  101. }
  102. if ($expr instanceof Expr\Array_) {
  103. return $this->evaluateArray($expr);
  104. }
  105. // Unary operators
  106. if ($expr instanceof Expr\UnaryPlus) {
  107. return +$this->evaluate($expr->expr);
  108. }
  109. if ($expr instanceof Expr\UnaryMinus) {
  110. return -$this->evaluate($expr->expr);
  111. }
  112. if ($expr instanceof Expr\BooleanNot) {
  113. return !$this->evaluate($expr->expr);
  114. }
  115. if ($expr instanceof Expr\BitwiseNot) {
  116. return ~$this->evaluate($expr->expr);
  117. }
  118. if ($expr instanceof Expr\BinaryOp) {
  119. return $this->evaluateBinaryOp($expr);
  120. }
  121. if ($expr instanceof Expr\Ternary) {
  122. return $this->evaluateTernary($expr);
  123. }
  124. if ($expr instanceof Expr\ArrayDimFetch && null !== $expr->dim) {
  125. return $this->evaluate($expr->var)[$this->evaluate($expr->dim)];
  126. }
  127. if ($expr instanceof Expr\ConstFetch) {
  128. return $this->evaluateConstFetch($expr);
  129. }
  130. return ($this->fallbackEvaluator)($expr);
  131. }
  132. private function evaluateArray(Expr\Array_ $expr) {
  133. $array = [];
  134. foreach ($expr->items as $item) {
  135. if (null !== $item->key) {
  136. $array[$this->evaluate($item->key)] = $this->evaluate($item->value);
  137. } else {
  138. $array[] = $this->evaluate($item->value);
  139. }
  140. }
  141. return $array;
  142. }
  143. private function evaluateTernary(Expr\Ternary $expr) {
  144. if (null === $expr->if) {
  145. return $this->evaluate($expr->cond) ?: $this->evaluate($expr->else);
  146. }
  147. return $this->evaluate($expr->cond)
  148. ? $this->evaluate($expr->if)
  149. : $this->evaluate($expr->else);
  150. }
  151. private function evaluateBinaryOp(Expr\BinaryOp $expr) {
  152. if ($expr instanceof Expr\BinaryOp\Coalesce
  153. && $expr->left instanceof Expr\ArrayDimFetch
  154. ) {
  155. // This needs to be special cased to respect BP_VAR_IS fetch semantics
  156. return $this->evaluate($expr->left->var)[$this->evaluate($expr->left->dim)]
  157. ?? $this->evaluate($expr->right);
  158. }
  159. // The evaluate() calls are repeated in each branch, because some of the operators are
  160. // short-circuiting and evaluating the RHS in advance may be illegal in that case
  161. $l = $expr->left;
  162. $r = $expr->right;
  163. switch ($expr->getOperatorSigil()) {
  164. case '&': return $this->evaluate($l) & $this->evaluate($r);
  165. case '|': return $this->evaluate($l) | $this->evaluate($r);
  166. case '^': return $this->evaluate($l) ^ $this->evaluate($r);
  167. case '&&': return $this->evaluate($l) && $this->evaluate($r);
  168. case '||': return $this->evaluate($l) || $this->evaluate($r);
  169. case '??': return $this->evaluate($l) ?? $this->evaluate($r);
  170. case '.': return $this->evaluate($l) . $this->evaluate($r);
  171. case '/': return $this->evaluate($l) / $this->evaluate($r);
  172. case '==': return $this->evaluate($l) == $this->evaluate($r);
  173. case '>': return $this->evaluate($l) > $this->evaluate($r);
  174. case '>=': return $this->evaluate($l) >= $this->evaluate($r);
  175. case '===': return $this->evaluate($l) === $this->evaluate($r);
  176. case 'and': return $this->evaluate($l) and $this->evaluate($r);
  177. case 'or': return $this->evaluate($l) or $this->evaluate($r);
  178. case 'xor': return $this->evaluate($l) xor $this->evaluate($r);
  179. case '-': return $this->evaluate($l) - $this->evaluate($r);
  180. case '%': return $this->evaluate($l) % $this->evaluate($r);
  181. case '*': return $this->evaluate($l) * $this->evaluate($r);
  182. case '!=': return $this->evaluate($l) != $this->evaluate($r);
  183. case '!==': return $this->evaluate($l) !== $this->evaluate($r);
  184. case '+': return $this->evaluate($l) + $this->evaluate($r);
  185. case '**': return $this->evaluate($l) ** $this->evaluate($r);
  186. case '<<': return $this->evaluate($l) << $this->evaluate($r);
  187. case '>>': return $this->evaluate($l) >> $this->evaluate($r);
  188. case '<': return $this->evaluate($l) < $this->evaluate($r);
  189. case '<=': return $this->evaluate($l) <= $this->evaluate($r);
  190. case '<=>': return $this->evaluate($l) <=> $this->evaluate($r);
  191. }
  192. throw new \Exception('Should not happen');
  193. }
  194. private function evaluateConstFetch(Expr\ConstFetch $expr) {
  195. $name = $expr->name->toLowerString();
  196. switch ($name) {
  197. case 'null': return null;
  198. case 'false': return false;
  199. case 'true': return true;
  200. }
  201. return ($this->fallbackEvaluator)($expr);
  202. }
  203. }