Parser.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\ExpressionLanguage;
  11. /**
  12. * Parsers a token stream.
  13. *
  14. * This parser implements a "Precedence climbing" algorithm.
  15. *
  16. * @see http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm
  17. * @see http://en.wikipedia.org/wiki/Operator-precedence_parser
  18. *
  19. * @author Fabien Potencier <fabien@symfony.com>
  20. */
  21. class Parser
  22. {
  23. public const OPERATOR_LEFT = 1;
  24. public const OPERATOR_RIGHT = 2;
  25. private $stream;
  26. private $unaryOperators;
  27. private $binaryOperators;
  28. private $functions;
  29. private $names;
  30. public function __construct(array $functions)
  31. {
  32. $this->functions = $functions;
  33. $this->unaryOperators = [
  34. 'not' => ['precedence' => 50],
  35. '!' => ['precedence' => 50],
  36. '-' => ['precedence' => 500],
  37. '+' => ['precedence' => 500],
  38. ];
  39. $this->binaryOperators = [
  40. 'or' => ['precedence' => 10, 'associativity' => self::OPERATOR_LEFT],
  41. '||' => ['precedence' => 10, 'associativity' => self::OPERATOR_LEFT],
  42. 'and' => ['precedence' => 15, 'associativity' => self::OPERATOR_LEFT],
  43. '&&' => ['precedence' => 15, 'associativity' => self::OPERATOR_LEFT],
  44. '|' => ['precedence' => 16, 'associativity' => self::OPERATOR_LEFT],
  45. '^' => ['precedence' => 17, 'associativity' => self::OPERATOR_LEFT],
  46. '&' => ['precedence' => 18, 'associativity' => self::OPERATOR_LEFT],
  47. '==' => ['precedence' => 20, 'associativity' => self::OPERATOR_LEFT],
  48. '===' => ['precedence' => 20, 'associativity' => self::OPERATOR_LEFT],
  49. '!=' => ['precedence' => 20, 'associativity' => self::OPERATOR_LEFT],
  50. '!==' => ['precedence' => 20, 'associativity' => self::OPERATOR_LEFT],
  51. '<' => ['precedence' => 20, 'associativity' => self::OPERATOR_LEFT],
  52. '>' => ['precedence' => 20, 'associativity' => self::OPERATOR_LEFT],
  53. '>=' => ['precedence' => 20, 'associativity' => self::OPERATOR_LEFT],
  54. '<=' => ['precedence' => 20, 'associativity' => self::OPERATOR_LEFT],
  55. 'not in' => ['precedence' => 20, 'associativity' => self::OPERATOR_LEFT],
  56. 'in' => ['precedence' => 20, 'associativity' => self::OPERATOR_LEFT],
  57. 'matches' => ['precedence' => 20, 'associativity' => self::OPERATOR_LEFT],
  58. '..' => ['precedence' => 25, 'associativity' => self::OPERATOR_LEFT],
  59. '+' => ['precedence' => 30, 'associativity' => self::OPERATOR_LEFT],
  60. '-' => ['precedence' => 30, 'associativity' => self::OPERATOR_LEFT],
  61. '~' => ['precedence' => 40, 'associativity' => self::OPERATOR_LEFT],
  62. '*' => ['precedence' => 60, 'associativity' => self::OPERATOR_LEFT],
  63. '/' => ['precedence' => 60, 'associativity' => self::OPERATOR_LEFT],
  64. '%' => ['precedence' => 60, 'associativity' => self::OPERATOR_LEFT],
  65. '**' => ['precedence' => 200, 'associativity' => self::OPERATOR_RIGHT],
  66. ];
  67. }
  68. /**
  69. * Converts a token stream to a node tree.
  70. *
  71. * The valid names is an array where the values
  72. * are the names that the user can use in an expression.
  73. *
  74. * If the variable name in the compiled PHP code must be
  75. * different, define it as the key.
  76. *
  77. * For instance, ['this' => 'container'] means that the
  78. * variable 'container' can be used in the expression
  79. * but the compiled code will use 'this'.
  80. *
  81. * @param array $names An array of valid names
  82. *
  83. * @return Node\Node A node tree
  84. *
  85. * @throws SyntaxError
  86. */
  87. public function parse(TokenStream $stream, $names = [])
  88. {
  89. $this->stream = $stream;
  90. $this->names = $names;
  91. $node = $this->parseExpression();
  92. if (!$stream->isEOF()) {
  93. throw new SyntaxError(sprintf('Unexpected token "%s" of value "%s".', $stream->current->type, $stream->current->value), $stream->current->cursor, $stream->getExpression());
  94. }
  95. return $node;
  96. }
  97. public function parseExpression($precedence = 0)
  98. {
  99. $expr = $this->getPrimary();
  100. $token = $this->stream->current;
  101. while ($token->test(Token::OPERATOR_TYPE) && isset($this->binaryOperators[$token->value]) && $this->binaryOperators[$token->value]['precedence'] >= $precedence) {
  102. $op = $this->binaryOperators[$token->value];
  103. $this->stream->next();
  104. $expr1 = $this->parseExpression(self::OPERATOR_LEFT === $op['associativity'] ? $op['precedence'] + 1 : $op['precedence']);
  105. $expr = new Node\BinaryNode($token->value, $expr, $expr1);
  106. $token = $this->stream->current;
  107. }
  108. if (0 === $precedence) {
  109. return $this->parseConditionalExpression($expr);
  110. }
  111. return $expr;
  112. }
  113. protected function getPrimary()
  114. {
  115. $token = $this->stream->current;
  116. if ($token->test(Token::OPERATOR_TYPE) && isset($this->unaryOperators[$token->value])) {
  117. $operator = $this->unaryOperators[$token->value];
  118. $this->stream->next();
  119. $expr = $this->parseExpression($operator['precedence']);
  120. return $this->parsePostfixExpression(new Node\UnaryNode($token->value, $expr));
  121. }
  122. if ($token->test(Token::PUNCTUATION_TYPE, '(')) {
  123. $this->stream->next();
  124. $expr = $this->parseExpression();
  125. $this->stream->expect(Token::PUNCTUATION_TYPE, ')', 'An opened parenthesis is not properly closed');
  126. return $this->parsePostfixExpression($expr);
  127. }
  128. return $this->parsePrimaryExpression();
  129. }
  130. protected function parseConditionalExpression($expr)
  131. {
  132. while ($this->stream->current->test(Token::PUNCTUATION_TYPE, '?')) {
  133. $this->stream->next();
  134. if (!$this->stream->current->test(Token::PUNCTUATION_TYPE, ':')) {
  135. $expr2 = $this->parseExpression();
  136. if ($this->stream->current->test(Token::PUNCTUATION_TYPE, ':')) {
  137. $this->stream->next();
  138. $expr3 = $this->parseExpression();
  139. } else {
  140. $expr3 = new Node\ConstantNode(null);
  141. }
  142. } else {
  143. $this->stream->next();
  144. $expr2 = $expr;
  145. $expr3 = $this->parseExpression();
  146. }
  147. $expr = new Node\ConditionalNode($expr, $expr2, $expr3);
  148. }
  149. return $expr;
  150. }
  151. public function parsePrimaryExpression()
  152. {
  153. $token = $this->stream->current;
  154. switch ($token->type) {
  155. case Token::NAME_TYPE:
  156. $this->stream->next();
  157. switch ($token->value) {
  158. case 'true':
  159. case 'TRUE':
  160. return new Node\ConstantNode(true);
  161. case 'false':
  162. case 'FALSE':
  163. return new Node\ConstantNode(false);
  164. case 'null':
  165. case 'NULL':
  166. return new Node\ConstantNode(null);
  167. default:
  168. if ('(' === $this->stream->current->value) {
  169. if (false === isset($this->functions[$token->value])) {
  170. throw new SyntaxError(sprintf('The function "%s" does not exist.', $token->value), $token->cursor, $this->stream->getExpression(), $token->value, array_keys($this->functions));
  171. }
  172. $node = new Node\FunctionNode($token->value, $this->parseArguments());
  173. } else {
  174. if (!\in_array($token->value, $this->names, true)) {
  175. throw new SyntaxError(sprintf('Variable "%s" is not valid.', $token->value), $token->cursor, $this->stream->getExpression(), $token->value, $this->names);
  176. }
  177. // is the name used in the compiled code different
  178. // from the name used in the expression?
  179. if (\is_int($name = array_search($token->value, $this->names))) {
  180. $name = $token->value;
  181. }
  182. $node = new Node\NameNode($name);
  183. }
  184. }
  185. break;
  186. case Token::NUMBER_TYPE:
  187. case Token::STRING_TYPE:
  188. $this->stream->next();
  189. return new Node\ConstantNode($token->value);
  190. default:
  191. if ($token->test(Token::PUNCTUATION_TYPE, '[')) {
  192. $node = $this->parseArrayExpression();
  193. } elseif ($token->test(Token::PUNCTUATION_TYPE, '{')) {
  194. $node = $this->parseHashExpression();
  195. } else {
  196. throw new SyntaxError(sprintf('Unexpected token "%s" of value "%s".', $token->type, $token->value), $token->cursor, $this->stream->getExpression());
  197. }
  198. }
  199. return $this->parsePostfixExpression($node);
  200. }
  201. public function parseArrayExpression()
  202. {
  203. $this->stream->expect(Token::PUNCTUATION_TYPE, '[', 'An array element was expected');
  204. $node = new Node\ArrayNode();
  205. $first = true;
  206. while (!$this->stream->current->test(Token::PUNCTUATION_TYPE, ']')) {
  207. if (!$first) {
  208. $this->stream->expect(Token::PUNCTUATION_TYPE, ',', 'An array element must be followed by a comma');
  209. // trailing ,?
  210. if ($this->stream->current->test(Token::PUNCTUATION_TYPE, ']')) {
  211. break;
  212. }
  213. }
  214. $first = false;
  215. $node->addElement($this->parseExpression());
  216. }
  217. $this->stream->expect(Token::PUNCTUATION_TYPE, ']', 'An opened array is not properly closed');
  218. return $node;
  219. }
  220. public function parseHashExpression()
  221. {
  222. $this->stream->expect(Token::PUNCTUATION_TYPE, '{', 'A hash element was expected');
  223. $node = new Node\ArrayNode();
  224. $first = true;
  225. while (!$this->stream->current->test(Token::PUNCTUATION_TYPE, '}')) {
  226. if (!$first) {
  227. $this->stream->expect(Token::PUNCTUATION_TYPE, ',', 'A hash value must be followed by a comma');
  228. // trailing ,?
  229. if ($this->stream->current->test(Token::PUNCTUATION_TYPE, '}')) {
  230. break;
  231. }
  232. }
  233. $first = false;
  234. // a hash key can be:
  235. //
  236. // * a number -- 12
  237. // * a string -- 'a'
  238. // * a name, which is equivalent to a string -- a
  239. // * an expression, which must be enclosed in parentheses -- (1 + 2)
  240. if ($this->stream->current->test(Token::STRING_TYPE) || $this->stream->current->test(Token::NAME_TYPE) || $this->stream->current->test(Token::NUMBER_TYPE)) {
  241. $key = new Node\ConstantNode($this->stream->current->value);
  242. $this->stream->next();
  243. } elseif ($this->stream->current->test(Token::PUNCTUATION_TYPE, '(')) {
  244. $key = $this->parseExpression();
  245. } else {
  246. $current = $this->stream->current;
  247. throw new SyntaxError(sprintf('A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "%s" of value "%s".', $current->type, $current->value), $current->cursor, $this->stream->getExpression());
  248. }
  249. $this->stream->expect(Token::PUNCTUATION_TYPE, ':', 'A hash key must be followed by a colon (:)');
  250. $value = $this->parseExpression();
  251. $node->addElement($value, $key);
  252. }
  253. $this->stream->expect(Token::PUNCTUATION_TYPE, '}', 'An opened hash is not properly closed');
  254. return $node;
  255. }
  256. public function parsePostfixExpression($node)
  257. {
  258. $token = $this->stream->current;
  259. while (Token::PUNCTUATION_TYPE == $token->type) {
  260. if ('.' === $token->value) {
  261. $this->stream->next();
  262. $token = $this->stream->current;
  263. $this->stream->next();
  264. if (
  265. Token::NAME_TYPE !== $token->type
  266. &&
  267. // Operators like "not" and "matches" are valid method or property names,
  268. //
  269. // In other words, besides NAME_TYPE, OPERATOR_TYPE could also be parsed as a property or method.
  270. // This is because operators are processed by the lexer prior to names. So "not" in "foo.not()" or "matches" in "foo.matches" will be recognized as an operator first.
  271. // But in fact, "not" and "matches" in such expressions shall be parsed as method or property names.
  272. //
  273. // And this ONLY works if the operator consists of valid characters for a property or method name.
  274. //
  275. // Other types, such as STRING_TYPE and NUMBER_TYPE, can't be parsed as property nor method names.
  276. //
  277. // As a result, if $token is NOT an operator OR $token->value is NOT a valid property or method name, an exception shall be thrown.
  278. (Token::OPERATOR_TYPE !== $token->type || !preg_match('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/A', $token->value))
  279. ) {
  280. throw new SyntaxError('Expected name.', $token->cursor, $this->stream->getExpression());
  281. }
  282. $arg = new Node\ConstantNode($token->value, true);
  283. $arguments = new Node\ArgumentsNode();
  284. if ($this->stream->current->test(Token::PUNCTUATION_TYPE, '(')) {
  285. $type = Node\GetAttrNode::METHOD_CALL;
  286. foreach ($this->parseArguments()->nodes as $n) {
  287. $arguments->addElement($n);
  288. }
  289. } else {
  290. $type = Node\GetAttrNode::PROPERTY_CALL;
  291. }
  292. $node = new Node\GetAttrNode($node, $arg, $arguments, $type);
  293. } elseif ('[' === $token->value) {
  294. $this->stream->next();
  295. $arg = $this->parseExpression();
  296. $this->stream->expect(Token::PUNCTUATION_TYPE, ']');
  297. $node = new Node\GetAttrNode($node, $arg, new Node\ArgumentsNode(), Node\GetAttrNode::ARRAY_CALL);
  298. } else {
  299. break;
  300. }
  301. $token = $this->stream->current;
  302. }
  303. return $node;
  304. }
  305. /**
  306. * Parses arguments.
  307. */
  308. public function parseArguments()
  309. {
  310. $args = [];
  311. $this->stream->expect(Token::PUNCTUATION_TYPE, '(', 'A list of arguments must begin with an opening parenthesis');
  312. while (!$this->stream->current->test(Token::PUNCTUATION_TYPE, ')')) {
  313. if (!empty($args)) {
  314. $this->stream->expect(Token::PUNCTUATION_TYPE, ',', 'Arguments must be separated by a comma');
  315. }
  316. $args[] = $this->parseExpression();
  317. }
  318. $this->stream->expect(Token::PUNCTUATION_TYPE, ')', 'A list of arguments must be closed by a parenthesis');
  319. return new Node\Node($args);
  320. }
  321. }