ExpressionParser.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 2009 Fabien Potencier
  6. * (c) 2009 Armin Ronacher
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. /**
  12. * Parses expressions.
  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. * @package twig
  20. * @author Fabien Potencier <fabien@symfony.com>
  21. */
  22. class Twig_ExpressionParser
  23. {
  24. const OPERATOR_LEFT = 1;
  25. const OPERATOR_RIGHT = 2;
  26. protected $parser;
  27. protected $unaryOperators;
  28. protected $binaryOperators;
  29. public function __construct(Twig_Parser $parser, array $unaryOperators, array $binaryOperators)
  30. {
  31. $this->parser = $parser;
  32. $this->unaryOperators = $unaryOperators;
  33. $this->binaryOperators = $binaryOperators;
  34. }
  35. public function parseExpression($precedence = 0)
  36. {
  37. $expr = $this->getPrimary();
  38. $token = $this->parser->getCurrentToken();
  39. while ($this->isBinary($token) && $this->binaryOperators[$token->getValue()]['precedence'] >= $precedence) {
  40. $op = $this->binaryOperators[$token->getValue()];
  41. $this->parser->getStream()->next();
  42. if (isset($op['callable'])) {
  43. $expr = call_user_func($op['callable'], $this->parser, $expr);
  44. } else {
  45. $expr1 = $this->parseExpression(self::OPERATOR_LEFT === $op['associativity'] ? $op['precedence'] + 1 : $op['precedence']);
  46. $class = $op['class'];
  47. $expr = new $class($expr, $expr1, $token->getLine());
  48. }
  49. $token = $this->parser->getCurrentToken();
  50. }
  51. if (0 === $precedence) {
  52. return $this->parseConditionalExpression($expr);
  53. }
  54. return $expr;
  55. }
  56. protected function getPrimary()
  57. {
  58. $token = $this->parser->getCurrentToken();
  59. if ($this->isUnary($token)) {
  60. $operator = $this->unaryOperators[$token->getValue()];
  61. $this->parser->getStream()->next();
  62. $expr = $this->parseExpression($operator['precedence']);
  63. $class = $operator['class'];
  64. return $this->parsePostfixExpression(new $class($expr, $token->getLine()));
  65. } elseif ($token->test(Twig_Token::PUNCTUATION_TYPE, '(')) {
  66. $this->parser->getStream()->next();
  67. $expr = $this->parseExpression();
  68. $this->parser->getStream()->expect(Twig_Token::PUNCTUATION_TYPE, ')', 'An opened parenthesis is not properly closed');
  69. return $this->parsePostfixExpression($expr);
  70. }
  71. return $this->parsePrimaryExpression();
  72. }
  73. protected function parseConditionalExpression($expr)
  74. {
  75. while ($this->parser->getStream()->test(Twig_Token::PUNCTUATION_TYPE, '?')) {
  76. $this->parser->getStream()->next();
  77. $expr2 = $this->parseExpression();
  78. $this->parser->getStream()->expect(Twig_Token::PUNCTUATION_TYPE, ':', 'The ternary operator must have a default value');
  79. $expr3 = $this->parseExpression();
  80. $expr = new Twig_Node_Expression_Conditional($expr, $expr2, $expr3, $this->parser->getCurrentToken()->getLine());
  81. }
  82. return $expr;
  83. }
  84. protected function isUnary(Twig_Token $token)
  85. {
  86. return $token->test(Twig_Token::OPERATOR_TYPE) && isset($this->unaryOperators[$token->getValue()]);
  87. }
  88. protected function isBinary(Twig_Token $token)
  89. {
  90. return $token->test(Twig_Token::OPERATOR_TYPE) && isset($this->binaryOperators[$token->getValue()]);
  91. }
  92. public function parsePrimaryExpression()
  93. {
  94. $token = $this->parser->getCurrentToken();
  95. switch ($token->getType()) {
  96. case Twig_Token::NAME_TYPE:
  97. $this->parser->getStream()->next();
  98. switch ($token->getValue()) {
  99. case 'true':
  100. case 'TRUE':
  101. $node = new Twig_Node_Expression_Constant(true, $token->getLine());
  102. break;
  103. case 'false':
  104. case 'FALSE':
  105. $node = new Twig_Node_Expression_Constant(false, $token->getLine());
  106. break;
  107. case 'none':
  108. case 'NONE':
  109. case 'null':
  110. case 'NULL':
  111. $node = new Twig_Node_Expression_Constant(null, $token->getLine());
  112. break;
  113. default:
  114. $node = new Twig_Node_Expression_Name($token->getValue(), $token->getLine());
  115. }
  116. break;
  117. case Twig_Token::NUMBER_TYPE:
  118. case Twig_Token::STRING_TYPE:
  119. $this->parser->getStream()->next();
  120. $node = new Twig_Node_Expression_Constant($token->getValue(), $token->getLine());
  121. break;
  122. default:
  123. if ($token->test(Twig_Token::PUNCTUATION_TYPE, '[')) {
  124. $node = $this->parseArrayExpression();
  125. } elseif ($token->test(Twig_Token::PUNCTUATION_TYPE, '{')) {
  126. $node = $this->parseHashExpression();
  127. } else {
  128. throw new Twig_Error_Syntax(sprintf('Unexpected token "%s" of value "%s"', Twig_Token::typeToEnglish($token->getType(), $token->getLine()), $token->getValue()), $token->getLine());
  129. }
  130. }
  131. return $this->parsePostfixExpression($node);
  132. }
  133. public function parseArrayExpression()
  134. {
  135. $stream = $this->parser->getStream();
  136. $stream->expect(Twig_Token::PUNCTUATION_TYPE, '[', 'An array element was expected');
  137. $elements = array();
  138. while (!$stream->test(Twig_Token::PUNCTUATION_TYPE, ']')) {
  139. if (!empty($elements)) {
  140. $stream->expect(Twig_Token::PUNCTUATION_TYPE, ',', 'An array element must be followed by a comma');
  141. // trailing ,?
  142. if ($stream->test(Twig_Token::PUNCTUATION_TYPE, ']')) {
  143. break;
  144. }
  145. }
  146. $elements[] = $this->parseExpression();
  147. }
  148. $stream->expect(Twig_Token::PUNCTUATION_TYPE, ']', 'An opened array is not properly closed');
  149. return new Twig_Node_Expression_Array($elements, $stream->getCurrent()->getLine());
  150. }
  151. public function parseHashExpression()
  152. {
  153. $stream = $this->parser->getStream();
  154. $stream->expect(Twig_Token::PUNCTUATION_TYPE, '{', 'A hash element was expected');
  155. $elements = array();
  156. while (!$stream->test(Twig_Token::PUNCTUATION_TYPE, '}')) {
  157. if (!empty($elements)) {
  158. $stream->expect(Twig_Token::PUNCTUATION_TYPE, ',', 'A hash value must be followed by a comma');
  159. // trailing ,?
  160. if ($stream->test(Twig_Token::PUNCTUATION_TYPE, '}')) {
  161. break;
  162. }
  163. }
  164. if (!$stream->test(Twig_Token::STRING_TYPE) && !$stream->test(Twig_Token::NUMBER_TYPE)) {
  165. $current = $stream->getCurrent();
  166. throw new Twig_Error_Syntax(sprintf('A hash key must be a quoted string or a number (unexpected token "%s" of value "%s"', Twig_Token::typeToEnglish($current->getType(), $current->getLine()), $current->getValue()), $current->getLine());
  167. }
  168. $key = $stream->next()->getValue();
  169. $stream->expect(Twig_Token::PUNCTUATION_TYPE, ':', 'A hash key must be followed by a colon (:)');
  170. $elements[$key] = $this->parseExpression();
  171. }
  172. $stream->expect(Twig_Token::PUNCTUATION_TYPE, '}', 'An opened hash is not properly closed');
  173. return new Twig_Node_Expression_Array($elements, $stream->getCurrent()->getLine());
  174. }
  175. public function parsePostfixExpression($node)
  176. {
  177. $firstPass = true;
  178. while (true) {
  179. $token = $this->parser->getCurrentToken();
  180. if ($token->getType() == Twig_Token::PUNCTUATION_TYPE) {
  181. if ('.' == $token->getValue() || '[' == $token->getValue()) {
  182. $node = $this->parseSubscriptExpression($node);
  183. } elseif ('|' == $token->getValue()) {
  184. $node = $this->parseFilterExpression($node);
  185. } elseif ($firstPass && $node instanceof Twig_Node_Expression_Name && '(' == $token->getValue()) {
  186. $node = $this->getFunctionNode($node);
  187. } else {
  188. break;
  189. }
  190. } else {
  191. break;
  192. }
  193. $firstPass = false;
  194. }
  195. return $node;
  196. }
  197. public function getFunctionNode(Twig_Node_Expression_Name $node)
  198. {
  199. $args = $this->parseArguments();
  200. if ('parent' === $node->getAttribute('name')) {
  201. if (!count($this->parser->getBlockStack())) {
  202. throw new Twig_Error_Syntax('Calling "parent" outside a block is forbidden', $node->getLine());
  203. }
  204. if (!$this->parser->getParent()) {
  205. throw new Twig_Error_Syntax('Calling "parent" on a template that does not extend another one is forbidden', $node->getLine());
  206. }
  207. return new Twig_Node_Expression_Parent($this->parser->peekBlockStack(), $node->getLine());
  208. }
  209. if ('block' === $node->getAttribute('name')) {
  210. return new Twig_Node_Expression_BlockReference($args->getNode(0), false, $node->getLine());
  211. }
  212. if (null !== $alias = $this->parser->getImportedFunction($node->getAttribute('name'))) {
  213. return new Twig_Node_Expression_GetAttr($alias['node'], new Twig_Node_Expression_Constant($alias['name'], $node->getLine()), $args, Twig_TemplateInterface::METHOD_CALL, $node->getLine());
  214. }
  215. return new Twig_Node_Expression_Function($node, $args, $node->getLine());
  216. }
  217. public function parseSubscriptExpression($node)
  218. {
  219. $token = $this->parser->getStream()->next();
  220. $lineno = $token->getLine();
  221. $arguments = new Twig_Node();
  222. $type = Twig_TemplateInterface::ANY_CALL;
  223. if ($token->getValue() == '.') {
  224. $token = $this->parser->getStream()->next();
  225. if (
  226. $token->getType() == Twig_Token::NAME_TYPE
  227. ||
  228. $token->getType() == Twig_Token::NUMBER_TYPE
  229. ||
  230. ($token->getType() == Twig_Token::OPERATOR_TYPE && preg_match(Twig_Lexer::REGEX_NAME, $token->getValue()))
  231. ) {
  232. $arg = new Twig_Node_Expression_Constant($token->getValue(), $lineno);
  233. if ($this->parser->getStream()->test(Twig_Token::PUNCTUATION_TYPE, '(')) {
  234. $type = Twig_TemplateInterface::METHOD_CALL;
  235. $arguments = $this->parseArguments();
  236. } else {
  237. $arguments = new Twig_Node();
  238. }
  239. } else {
  240. throw new Twig_Error_Syntax('Expected name or number', $lineno);
  241. }
  242. } else {
  243. $type = Twig_TemplateInterface::ARRAY_CALL;
  244. $arg = $this->parseExpression();
  245. $this->parser->getStream()->expect(Twig_Token::PUNCTUATION_TYPE, ']');
  246. }
  247. return new Twig_Node_Expression_GetAttr($node, $arg, $arguments, $type, $lineno);
  248. }
  249. public function parseFilterExpression($node)
  250. {
  251. $this->parser->getStream()->next();
  252. return $this->parseFilterExpressionRaw($node);
  253. }
  254. public function parseFilterExpressionRaw($node, $tag = null)
  255. {
  256. while (true) {
  257. $token = $this->parser->getStream()->expect(Twig_Token::NAME_TYPE);
  258. $name = new Twig_Node_Expression_Constant($token->getValue(), $token->getLine());
  259. if (!$this->parser->getStream()->test(Twig_Token::PUNCTUATION_TYPE, '(')) {
  260. $arguments = new Twig_Node();
  261. } else {
  262. $arguments = $this->parseArguments();
  263. }
  264. $node = new Twig_Node_Expression_Filter($node, $name, $arguments, $token->getLine(), $tag);
  265. if (!$this->parser->getStream()->test(Twig_Token::PUNCTUATION_TYPE, '|')) {
  266. break;
  267. }
  268. $this->parser->getStream()->next();
  269. }
  270. return $node;
  271. }
  272. public function parseArguments()
  273. {
  274. $args = array();
  275. $stream = $this->parser->getStream();
  276. $stream->expect(Twig_Token::PUNCTUATION_TYPE, '(', 'A list of arguments must be opened by a parenthesis');
  277. while (!$stream->test(Twig_Token::PUNCTUATION_TYPE, ')')) {
  278. if (!empty($args)) {
  279. $stream->expect(Twig_Token::PUNCTUATION_TYPE, ',', 'Arguments must be separated by a comma');
  280. }
  281. $args[] = $this->parseExpression();
  282. }
  283. $stream->expect(Twig_Token::PUNCTUATION_TYPE, ')', 'A list of arguments must be closed by a parenthesis');
  284. return new Twig_Node($args);
  285. }
  286. public function parseAssignmentExpression()
  287. {
  288. $targets = array();
  289. while (true) {
  290. $token = $this->parser->getStream()->expect(Twig_Token::NAME_TYPE, null, 'Only variables can be assigned to');
  291. if (in_array($token->getValue(), array('true', 'false', 'none'))) {
  292. throw new Twig_Error_Syntax(sprintf('You cannot assign a value to "%s"', $token->getValue()), $token->getLine());
  293. }
  294. $targets[] = new Twig_Node_Expression_AssignName($token->getValue(), $token->getLine());
  295. if (!$this->parser->getStream()->test(Twig_Token::PUNCTUATION_TYPE, ',')) {
  296. break;
  297. }
  298. $this->parser->getStream()->next();
  299. }
  300. return new Twig_Node($targets);
  301. }
  302. public function parseMultitargetExpression()
  303. {
  304. $targets = array();
  305. while (true) {
  306. $targets[] = $this->parseExpression();
  307. if (!$this->parser->getStream()->test(Twig_Token::PUNCTUATION_TYPE, ',')) {
  308. break;
  309. }
  310. $this->parser->getStream()->next();
  311. }
  312. return new Twig_Node($targets);
  313. }
  314. }