ExpressionParser.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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. if ('(' === $this->parser->getCurrentToken()->getValue()) {
  115. $node = $this->getFunctionNode($token->getValue(), $token->getLine());
  116. } else {
  117. $node = new Twig_Node_Expression_Name($token->getValue(), $token->getLine());
  118. }
  119. }
  120. break;
  121. case Twig_Token::NUMBER_TYPE:
  122. case Twig_Token::STRING_TYPE:
  123. $this->parser->getStream()->next();
  124. $node = new Twig_Node_Expression_Constant($token->getValue(), $token->getLine());
  125. break;
  126. default:
  127. if ($token->test(Twig_Token::PUNCTUATION_TYPE, '[')) {
  128. $node = $this->parseArrayExpression();
  129. } elseif ($token->test(Twig_Token::PUNCTUATION_TYPE, '{')) {
  130. $node = $this->parseHashExpression();
  131. } else {
  132. throw new Twig_Error_Syntax(sprintf('Unexpected token "%s" of value "%s"', Twig_Token::typeToEnglish($token->getType(), $token->getLine()), $token->getValue()), $token->getLine());
  133. }
  134. }
  135. return $this->parsePostfixExpression($node);
  136. }
  137. public function parseArrayExpression()
  138. {
  139. $stream = $this->parser->getStream();
  140. $stream->expect(Twig_Token::PUNCTUATION_TYPE, '[', 'An array element was expected');
  141. $elements = array();
  142. while (!$stream->test(Twig_Token::PUNCTUATION_TYPE, ']')) {
  143. if (!empty($elements)) {
  144. $stream->expect(Twig_Token::PUNCTUATION_TYPE, ',', 'An array element must be followed by a comma');
  145. // trailing ,?
  146. if ($stream->test(Twig_Token::PUNCTUATION_TYPE, ']')) {
  147. break;
  148. }
  149. }
  150. $elements[] = $this->parseExpression();
  151. }
  152. $stream->expect(Twig_Token::PUNCTUATION_TYPE, ']', 'An opened array is not properly closed');
  153. return new Twig_Node_Expression_Array($elements, $stream->getCurrent()->getLine());
  154. }
  155. public function parseHashExpression()
  156. {
  157. $stream = $this->parser->getStream();
  158. $stream->expect(Twig_Token::PUNCTUATION_TYPE, '{', 'A hash element was expected');
  159. $elements = array();
  160. while (!$stream->test(Twig_Token::PUNCTUATION_TYPE, '}')) {
  161. if (!empty($elements)) {
  162. $stream->expect(Twig_Token::PUNCTUATION_TYPE, ',', 'A hash value must be followed by a comma');
  163. // trailing ,?
  164. if ($stream->test(Twig_Token::PUNCTUATION_TYPE, '}')) {
  165. break;
  166. }
  167. }
  168. if (!$stream->test(Twig_Token::STRING_TYPE) && !$stream->test(Twig_Token::NUMBER_TYPE)) {
  169. $current = $stream->getCurrent();
  170. 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());
  171. }
  172. $key = $stream->next()->getValue();
  173. $stream->expect(Twig_Token::PUNCTUATION_TYPE, ':', 'A hash key must be followed by a colon (:)');
  174. $elements[$key] = $this->parseExpression();
  175. }
  176. $stream->expect(Twig_Token::PUNCTUATION_TYPE, '}', 'An opened hash is not properly closed');
  177. return new Twig_Node_Expression_Array($elements, $stream->getCurrent()->getLine());
  178. }
  179. public function parsePostfixExpression($node)
  180. {
  181. while (true) {
  182. $token = $this->parser->getCurrentToken();
  183. if ($token->getType() == Twig_Token::PUNCTUATION_TYPE) {
  184. if ('.' == $token->getValue() || '[' == $token->getValue()) {
  185. $node = $this->parseSubscriptExpression($node);
  186. } elseif ('|' == $token->getValue()) {
  187. $node = $this->parseFilterExpression($node);
  188. } else {
  189. break;
  190. }
  191. } else {
  192. break;
  193. }
  194. }
  195. return $node;
  196. }
  197. public function getFunctionNode($name, $line)
  198. {
  199. $args = $this->parseArguments();
  200. switch ($name) {
  201. case 'parent':
  202. if (!count($this->parser->getBlockStack())) {
  203. throw new Twig_Error_Syntax('Calling "parent" outside a block is forbidden', $line);
  204. }
  205. if (!$this->parser->getParent() && !$this->parser->hasTraits()) {
  206. throw new Twig_Error_Syntax('Calling "parent" on a template that does not extend nor "use" another template is forbidden', $line);
  207. }
  208. return new Twig_Node_Expression_Parent($this->parser->peekBlockStack(), $line);
  209. case 'block':
  210. return new Twig_Node_Expression_BlockReference($args->getNode(0), false, $line);
  211. case 'attribute':
  212. if (count($args) < 2) {
  213. throw new Twig_Error_Syntax('The "attribute" function takes at least two arguments (the variable and the attribute)', $line);
  214. }
  215. return new Twig_Node_Expression_GetAttr($args->getNode(0), $args->getNode(1), count($args) > 2 ? $args->getNode(2) : new Twig_Node_Expression_Array(array(), $line), Twig_TemplateInterface::ANY_CALL, $line);
  216. default:
  217. if (null !== $alias = $this->parser->getImportedFunction($name)) {
  218. return new Twig_Node_Expression_GetAttr($alias['node'], new Twig_Node_Expression_Constant($alias['name'], $line), $args, Twig_TemplateInterface::METHOD_CALL, $line);
  219. }
  220. $class = $this->getFunctionNodeClass($name);
  221. return new $class($name, $args, $line);
  222. }
  223. }
  224. public function parseSubscriptExpression($node)
  225. {
  226. $token = $this->parser->getStream()->next();
  227. $lineno = $token->getLine();
  228. $arguments = new Twig_Node();
  229. $type = Twig_TemplateInterface::ANY_CALL;
  230. if ($token->getValue() == '.') {
  231. $token = $this->parser->getStream()->next();
  232. if (
  233. $token->getType() == Twig_Token::NAME_TYPE
  234. ||
  235. $token->getType() == Twig_Token::NUMBER_TYPE
  236. ||
  237. ($token->getType() == Twig_Token::OPERATOR_TYPE && preg_match(Twig_Lexer::REGEX_NAME, $token->getValue()))
  238. ) {
  239. $arg = new Twig_Node_Expression_Constant($token->getValue(), $lineno);
  240. if ($this->parser->getStream()->test(Twig_Token::PUNCTUATION_TYPE, '(')) {
  241. $type = Twig_TemplateInterface::METHOD_CALL;
  242. $arguments = $this->parseArguments();
  243. } else {
  244. $arguments = new Twig_Node();
  245. }
  246. } else {
  247. throw new Twig_Error_Syntax('Expected name or number', $lineno);
  248. }
  249. } else {
  250. $type = Twig_TemplateInterface::ARRAY_CALL;
  251. $arg = $this->parseExpression();
  252. $this->parser->getStream()->expect(Twig_Token::PUNCTUATION_TYPE, ']');
  253. }
  254. return new Twig_Node_Expression_GetAttr($node, $arg, $arguments, $type, $lineno);
  255. }
  256. public function parseFilterExpression($node)
  257. {
  258. $this->parser->getStream()->next();
  259. return $this->parseFilterExpressionRaw($node);
  260. }
  261. public function parseFilterExpressionRaw($node, $tag = null)
  262. {
  263. while (true) {
  264. $token = $this->parser->getStream()->expect(Twig_Token::NAME_TYPE);
  265. $name = new Twig_Node_Expression_Constant($token->getValue(), $token->getLine());
  266. if (!$this->parser->getStream()->test(Twig_Token::PUNCTUATION_TYPE, '(')) {
  267. $arguments = new Twig_Node();
  268. } else {
  269. $arguments = $this->parseArguments();
  270. }
  271. $class = $this->getFilterNodeClass($name->getAttribute('value'));
  272. $node = new $class($node, $name, $arguments, $token->getLine(), $tag);
  273. if (!$this->parser->getStream()->test(Twig_Token::PUNCTUATION_TYPE, '|')) {
  274. break;
  275. }
  276. $this->parser->getStream()->next();
  277. }
  278. return $node;
  279. }
  280. public function parseArguments()
  281. {
  282. $args = array();
  283. $stream = $this->parser->getStream();
  284. $stream->expect(Twig_Token::PUNCTUATION_TYPE, '(', 'A list of arguments must be opened by a parenthesis');
  285. while (!$stream->test(Twig_Token::PUNCTUATION_TYPE, ')')) {
  286. if (!empty($args)) {
  287. $stream->expect(Twig_Token::PUNCTUATION_TYPE, ',', 'Arguments must be separated by a comma');
  288. }
  289. $args[] = $this->parseExpression();
  290. }
  291. $stream->expect(Twig_Token::PUNCTUATION_TYPE, ')', 'A list of arguments must be closed by a parenthesis');
  292. return new Twig_Node($args);
  293. }
  294. public function parseAssignmentExpression()
  295. {
  296. $targets = array();
  297. while (true) {
  298. $token = $this->parser->getStream()->expect(Twig_Token::NAME_TYPE, null, 'Only variables can be assigned to');
  299. if (in_array($token->getValue(), array('true', 'false', 'none'))) {
  300. throw new Twig_Error_Syntax(sprintf('You cannot assign a value to "%s"', $token->getValue()), $token->getLine());
  301. }
  302. $targets[] = new Twig_Node_Expression_AssignName($token->getValue(), $token->getLine());
  303. if (!$this->parser->getStream()->test(Twig_Token::PUNCTUATION_TYPE, ',')) {
  304. break;
  305. }
  306. $this->parser->getStream()->next();
  307. }
  308. return new Twig_Node($targets);
  309. }
  310. public function parseMultitargetExpression()
  311. {
  312. $targets = array();
  313. while (true) {
  314. $targets[] = $this->parseExpression();
  315. if (!$this->parser->getStream()->test(Twig_Token::PUNCTUATION_TYPE, ',')) {
  316. break;
  317. }
  318. $this->parser->getStream()->next();
  319. }
  320. return new Twig_Node($targets);
  321. }
  322. protected function getFunctionNodeClass($name)
  323. {
  324. $functionMap = $this->parser->getEnvironment()->getFunctions();
  325. if (isset($functionMap[$name]) && $functionMap[$name] instanceof Twig_Filter_Node) {
  326. return $functionMap[$name]->getClass();
  327. }
  328. return 'Twig_Node_Expression_Function';
  329. }
  330. protected function getFilterNodeClass($name)
  331. {
  332. $filterMap = $this->parser->getEnvironment()->getFilters();
  333. if (isset($filterMap[$name]) && $filterMap[$name] instanceof Twig_Filter_Node) {
  334. return $filterMap[$name]->getClass();
  335. }
  336. return 'Twig_Node_Expression_Filter';
  337. }
  338. }