ExpressionParser.php 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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. $this->parser->getStream()->next();
  123. $node = new Twig_Node_Expression_Constant($token->getValue(), $token->getLine());
  124. break;
  125. case Twig_Token::STRING_TYPE:
  126. case Twig_Token::INTERPOLATION_START_TYPE:
  127. $node = $this->parseStringExpression();
  128. break;
  129. default:
  130. if ($token->test(Twig_Token::PUNCTUATION_TYPE, '[')) {
  131. $node = $this->parseArrayExpression();
  132. } elseif ($token->test(Twig_Token::PUNCTUATION_TYPE, '{')) {
  133. $node = $this->parseHashExpression();
  134. } else {
  135. throw new Twig_Error_Syntax(sprintf('Unexpected token "%s" of value "%s"', Twig_Token::typeToEnglish($token->getType(), $token->getLine()), $token->getValue()), $token->getLine());
  136. }
  137. }
  138. return $this->parsePostfixExpression($node);
  139. }
  140. public function parseStringExpression()
  141. {
  142. $stream = $this->parser->getStream();
  143. $nodes = array();
  144. // a string cannot be followed by another string in a single expression
  145. $nextCanBeString = true;
  146. while (true) {
  147. if ($stream->test(Twig_Token::STRING_TYPE) && $nextCanBeString) {
  148. $token = $stream->next();
  149. $nodes[] = new Twig_Node_Expression_Constant($token->getValue(), $token->getLine());
  150. $nextCanBeString = false;
  151. } elseif ($stream->test(Twig_Token::INTERPOLATION_START_TYPE)) {
  152. $stream->next();
  153. $nodes[] = $this->parseExpression();
  154. $stream->expect(Twig_Token::INTERPOLATION_END_TYPE);
  155. $nextCanBeString = true;
  156. } else {
  157. break;
  158. }
  159. }
  160. $expr = array_shift($nodes);
  161. foreach ($nodes as $node) {
  162. $expr = new Twig_Node_Expression_Binary_Concat($expr, $node, $node->getLine());
  163. }
  164. return $expr;
  165. }
  166. public function parseArrayExpression()
  167. {
  168. $stream = $this->parser->getStream();
  169. $stream->expect(Twig_Token::PUNCTUATION_TYPE, '[', 'An array element was expected');
  170. $node = new Twig_Node_Expression_Array(array(), $stream->getCurrent()->getLine());
  171. $first = true;
  172. while (!$stream->test(Twig_Token::PUNCTUATION_TYPE, ']')) {
  173. if (!$first) {
  174. $stream->expect(Twig_Token::PUNCTUATION_TYPE, ',', 'An array element must be followed by a comma');
  175. // trailing ,?
  176. if ($stream->test(Twig_Token::PUNCTUATION_TYPE, ']')) {
  177. break;
  178. }
  179. }
  180. $first = false;
  181. $node->addElement($this->parseExpression());
  182. }
  183. $stream->expect(Twig_Token::PUNCTUATION_TYPE, ']', 'An opened array is not properly closed');
  184. return $node;
  185. }
  186. public function parseHashExpression()
  187. {
  188. $stream = $this->parser->getStream();
  189. $stream->expect(Twig_Token::PUNCTUATION_TYPE, '{', 'A hash element was expected');
  190. $node = new Twig_Node_Expression_Array(array(), $stream->getCurrent()->getLine());
  191. $first = true;
  192. while (!$stream->test(Twig_Token::PUNCTUATION_TYPE, '}')) {
  193. if (!$first) {
  194. $stream->expect(Twig_Token::PUNCTUATION_TYPE, ',', 'A hash value must be followed by a comma');
  195. // trailing ,?
  196. if ($stream->test(Twig_Token::PUNCTUATION_TYPE, '}')) {
  197. break;
  198. }
  199. }
  200. $first = false;
  201. // a hash key can be:
  202. //
  203. // * a number -- 12
  204. // * a string -- 'a'
  205. // * a name, which is equivalent to a string -- a
  206. // * an expression, which must be enclosed in parentheses -- (1 + 2)
  207. if ($stream->test(Twig_Token::STRING_TYPE) || $stream->test(Twig_Token::NAME_TYPE) || $stream->test(Twig_Token::NUMBER_TYPE)) {
  208. $token = $stream->next();
  209. $key = new Twig_Node_Expression_Constant($token->getValue(), $token->getLine());
  210. } elseif ($stream->test(Twig_Token::PUNCTUATION_TYPE, '(')) {
  211. $key = $this->parseExpression();
  212. } else {
  213. $current = $stream->getCurrent();
  214. throw new Twig_Error_Syntax(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"', Twig_Token::typeToEnglish($current->getType(), $current->getLine()), $current->getValue()), $current->getLine());
  215. }
  216. $stream->expect(Twig_Token::PUNCTUATION_TYPE, ':', 'A hash key must be followed by a colon (:)');
  217. $value = $this->parseExpression();
  218. $node->addElement($value, $key);
  219. }
  220. $stream->expect(Twig_Token::PUNCTUATION_TYPE, '}', 'An opened hash is not properly closed');
  221. return $node;
  222. }
  223. public function parsePostfixExpression($node)
  224. {
  225. while (true) {
  226. $token = $this->parser->getCurrentToken();
  227. if ($token->getType() == Twig_Token::PUNCTUATION_TYPE) {
  228. if ('.' == $token->getValue() || '[' == $token->getValue()) {
  229. $node = $this->parseSubscriptExpression($node);
  230. } elseif ('|' == $token->getValue()) {
  231. $node = $this->parseFilterExpression($node);
  232. } else {
  233. break;
  234. }
  235. } else {
  236. break;
  237. }
  238. }
  239. return $node;
  240. }
  241. public function getFunctionNode($name, $line)
  242. {
  243. $args = $this->parseArguments();
  244. switch ($name) {
  245. case 'parent':
  246. if (!count($this->parser->getBlockStack())) {
  247. throw new Twig_Error_Syntax('Calling "parent" outside a block is forbidden', $line);
  248. }
  249. if (!$this->parser->getParent() && !$this->parser->hasTraits()) {
  250. throw new Twig_Error_Syntax('Calling "parent" on a template that does not extend nor "use" another template is forbidden', $line);
  251. }
  252. return new Twig_Node_Expression_Parent($this->parser->peekBlockStack(), $line);
  253. case 'block':
  254. return new Twig_Node_Expression_BlockReference($args->getNode(0), false, $line);
  255. case 'attribute':
  256. if (count($args) < 2) {
  257. throw new Twig_Error_Syntax('The "attribute" function takes at least two arguments (the variable and the attributes)', $line);
  258. }
  259. 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);
  260. default:
  261. if (null !== $alias = $this->parser->getImportedFunction($name)) {
  262. $arguments = new Twig_Node_Expression_Array(array(), $line);
  263. foreach ($args as $n) {
  264. $arguments->addElement($n);
  265. }
  266. $node = new Twig_Node_Expression_MethodCall($alias['node'], $alias['name'], $arguments, $line);
  267. $node->setAttribute('safe', true);
  268. return $node;
  269. }
  270. $class = $this->getFunctionNodeClass($name);
  271. return new $class($name, $args, $line);
  272. }
  273. }
  274. public function parseSubscriptExpression($node)
  275. {
  276. $stream = $this->parser->getStream();
  277. $token = $stream->next();
  278. $lineno = $token->getLine();
  279. $arguments = new Twig_Node_Expression_Array(array(), $lineno);
  280. $type = Twig_TemplateInterface::ANY_CALL;
  281. if ($token->getValue() == '.') {
  282. $token = $stream->next();
  283. if (
  284. $token->getType() == Twig_Token::NAME_TYPE
  285. ||
  286. $token->getType() == Twig_Token::NUMBER_TYPE
  287. ||
  288. ($token->getType() == Twig_Token::OPERATOR_TYPE && preg_match(Twig_Lexer::REGEX_NAME, $token->getValue()))
  289. ) {
  290. $arg = new Twig_Node_Expression_Constant($token->getValue(), $lineno);
  291. if ($stream->test(Twig_Token::PUNCTUATION_TYPE, '(')) {
  292. $type = Twig_TemplateInterface::METHOD_CALL;
  293. foreach ($this->parseArguments() as $n) {
  294. $arguments->addElement($n);
  295. }
  296. }
  297. } else {
  298. throw new Twig_Error_Syntax('Expected name or number', $lineno);
  299. }
  300. } else {
  301. $type = Twig_TemplateInterface::ARRAY_CALL;
  302. $arg = $this->parseExpression();
  303. // slice?
  304. if ($stream->test(Twig_Token::PUNCTUATION_TYPE, ':')) {
  305. $stream->next();
  306. if ($stream->test(Twig_Token::PUNCTUATION_TYPE, ']')) {
  307. $length = new Twig_Node_Expression_Constant(null, $token->getLine());
  308. } else {
  309. $length = $this->parseExpression();
  310. }
  311. $class = $this->getFilterNodeClass('slice');
  312. $arguments = new Twig_Node(array($arg, $length));
  313. $filter = new $class($node, new Twig_Node_Expression_Constant('slice', $token->getLine()), $arguments, $token->getLine());
  314. $stream->expect(Twig_Token::PUNCTUATION_TYPE, ']');
  315. return $filter;
  316. }
  317. $stream->expect(Twig_Token::PUNCTUATION_TYPE, ']');
  318. }
  319. return new Twig_Node_Expression_GetAttr($node, $arg, $arguments, $type, $lineno);
  320. }
  321. public function parseFilterExpression($node)
  322. {
  323. $this->parser->getStream()->next();
  324. return $this->parseFilterExpressionRaw($node);
  325. }
  326. public function parseFilterExpressionRaw($node, $tag = null)
  327. {
  328. while (true) {
  329. $token = $this->parser->getStream()->expect(Twig_Token::NAME_TYPE);
  330. $name = new Twig_Node_Expression_Constant($token->getValue(), $token->getLine());
  331. if (!$this->parser->getStream()->test(Twig_Token::PUNCTUATION_TYPE, '(')) {
  332. $arguments = new Twig_Node();
  333. } else {
  334. $arguments = $this->parseArguments();
  335. }
  336. $class = $this->getFilterNodeClass($name->getAttribute('value'));
  337. $node = new $class($node, $name, $arguments, $token->getLine(), $tag);
  338. if (!$this->parser->getStream()->test(Twig_Token::PUNCTUATION_TYPE, '|')) {
  339. break;
  340. }
  341. $this->parser->getStream()->next();
  342. }
  343. return $node;
  344. }
  345. public function parseArguments()
  346. {
  347. $args = array();
  348. $stream = $this->parser->getStream();
  349. $stream->expect(Twig_Token::PUNCTUATION_TYPE, '(', 'A list of arguments must be opened by a parenthesis');
  350. while (!$stream->test(Twig_Token::PUNCTUATION_TYPE, ')')) {
  351. if (!empty($args)) {
  352. $stream->expect(Twig_Token::PUNCTUATION_TYPE, ',', 'Arguments must be separated by a comma');
  353. }
  354. $args[] = $this->parseExpression();
  355. }
  356. $stream->expect(Twig_Token::PUNCTUATION_TYPE, ')', 'A list of arguments must be closed by a parenthesis');
  357. return new Twig_Node($args);
  358. }
  359. public function parseAssignmentExpression()
  360. {
  361. $targets = array();
  362. while (true) {
  363. $token = $this->parser->getStream()->expect(Twig_Token::NAME_TYPE, null, 'Only variables can be assigned to');
  364. if (in_array($token->getValue(), array('true', 'false', 'none'))) {
  365. throw new Twig_Error_Syntax(sprintf('You cannot assign a value to "%s"', $token->getValue()), $token->getLine());
  366. }
  367. $targets[] = new Twig_Node_Expression_AssignName($token->getValue(), $token->getLine());
  368. if (!$this->parser->getStream()->test(Twig_Token::PUNCTUATION_TYPE, ',')) {
  369. break;
  370. }
  371. $this->parser->getStream()->next();
  372. }
  373. return new Twig_Node($targets);
  374. }
  375. public function parseMultitargetExpression()
  376. {
  377. $targets = array();
  378. while (true) {
  379. $targets[] = $this->parseExpression();
  380. if (!$this->parser->getStream()->test(Twig_Token::PUNCTUATION_TYPE, ',')) {
  381. break;
  382. }
  383. $this->parser->getStream()->next();
  384. }
  385. return new Twig_Node($targets);
  386. }
  387. protected function getFunctionNodeClass($name)
  388. {
  389. $functionMap = $this->parser->getEnvironment()->getFunctions();
  390. if (isset($functionMap[$name]) && $functionMap[$name] instanceof Twig_Function_Node) {
  391. return $functionMap[$name]->getClass();
  392. }
  393. return 'Twig_Node_Expression_Function';
  394. }
  395. protected function getFilterNodeClass($name)
  396. {
  397. $filterMap = $this->parser->getEnvironment()->getFilters();
  398. if (isset($filterMap[$name]) && $filterMap[$name] instanceof Twig_Filter_Node) {
  399. return $filterMap[$name]->getClass();
  400. }
  401. return 'Twig_Node_Expression_Filter';
  402. }
  403. }