Parser.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. * Default parser implementation.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class Twig_Parser implements Twig_ParserInterface
  17. {
  18. protected $stack = array();
  19. protected $stream;
  20. protected $parent;
  21. protected $handlers;
  22. protected $visitors;
  23. protected $expressionParser;
  24. protected $blocks;
  25. protected $blockStack;
  26. protected $macros;
  27. protected $env;
  28. protected $reservedMacroNames;
  29. protected $importedSymbols;
  30. protected $traits;
  31. protected $embeddedTemplates = array();
  32. /**
  33. * Constructor.
  34. *
  35. * @param Twig_Environment $env A Twig_Environment instance
  36. */
  37. public function __construct(Twig_Environment $env)
  38. {
  39. $this->env = $env;
  40. }
  41. public function getEnvironment()
  42. {
  43. return $this->env;
  44. }
  45. public function getVarName()
  46. {
  47. return sprintf('__internal_%s', hash('sha256', uniqid(mt_rand(), true), false));
  48. }
  49. public function getFilename()
  50. {
  51. return $this->stream->getFilename();
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. public function parse(Twig_TokenStream $stream, $test = null, $dropNeedle = false)
  57. {
  58. // push all variables into the stack to keep the current state of the parser
  59. // using get_object_vars() instead of foreach would lead to https://bugs.php.net/71336
  60. $vars = array();
  61. foreach ($this as $k => $v) {
  62. $vars[$k] = $v;
  63. }
  64. unset($vars['stack'], $vars['env'], $vars['handlers'], $vars['visitors'], $vars['expressionParser'], $vars['reservedMacroNames']);
  65. $this->stack[] = $vars;
  66. // tag handlers
  67. if (null === $this->handlers) {
  68. $this->handlers = $this->env->getTokenParsers();
  69. $this->handlers->setParser($this);
  70. }
  71. // node visitors
  72. if (null === $this->visitors) {
  73. $this->visitors = $this->env->getNodeVisitors();
  74. }
  75. if (null === $this->expressionParser) {
  76. $this->expressionParser = new Twig_ExpressionParser($this, $this->env->getUnaryOperators(), $this->env->getBinaryOperators());
  77. }
  78. $this->stream = $stream;
  79. $this->parent = null;
  80. $this->blocks = array();
  81. $this->macros = array();
  82. $this->traits = array();
  83. $this->blockStack = array();
  84. $this->importedSymbols = array(array());
  85. $this->embeddedTemplates = array();
  86. try {
  87. $body = $this->subparse($test, $dropNeedle);
  88. if (null !== $this->parent && null === $body = $this->filterBodyNodes($body)) {
  89. $body = new Twig_Node();
  90. }
  91. } catch (Twig_Error_Syntax $e) {
  92. if (!$e->getTemplateFile()) {
  93. $e->setTemplateFile($this->getFilename());
  94. }
  95. if (!$e->getTemplateLine()) {
  96. $e->setTemplateLine($this->stream->getCurrent()->getLine());
  97. }
  98. throw $e;
  99. }
  100. $node = new Twig_Node_Module(new Twig_Node_Body(array($body)), $this->parent, new Twig_Node($this->blocks), new Twig_Node($this->macros), new Twig_Node($this->traits), $this->embeddedTemplates, $this->getFilename());
  101. $traverser = new Twig_NodeTraverser($this->env, $this->visitors);
  102. $node = $traverser->traverse($node);
  103. // restore previous stack so previous parse() call can resume working
  104. foreach (array_pop($this->stack) as $key => $val) {
  105. $this->$key = $val;
  106. }
  107. return $node;
  108. }
  109. public function subparse($test, $dropNeedle = false)
  110. {
  111. $lineno = $this->getCurrentToken()->getLine();
  112. $rv = array();
  113. while (!$this->stream->isEOF()) {
  114. switch ($this->getCurrentToken()->getType()) {
  115. case Twig_Token::TEXT_TYPE:
  116. $token = $this->stream->next();
  117. $rv[] = new Twig_Node_Text($token->getValue(), $token->getLine());
  118. break;
  119. case Twig_Token::VAR_START_TYPE:
  120. $token = $this->stream->next();
  121. $expr = $this->expressionParser->parseExpression();
  122. $this->stream->expect(Twig_Token::VAR_END_TYPE);
  123. $rv[] = new Twig_Node_Print($expr, $token->getLine());
  124. break;
  125. case Twig_Token::BLOCK_START_TYPE:
  126. $this->stream->next();
  127. $token = $this->getCurrentToken();
  128. if ($token->getType() !== Twig_Token::NAME_TYPE) {
  129. throw new Twig_Error_Syntax('A block must start with a tag name.', $token->getLine(), $this->getFilename());
  130. }
  131. if (null !== $test && call_user_func($test, $token)) {
  132. if ($dropNeedle) {
  133. $this->stream->next();
  134. }
  135. if (1 === count($rv)) {
  136. return $rv[0];
  137. }
  138. return new Twig_Node($rv, array(), $lineno);
  139. }
  140. $subparser = $this->handlers->getTokenParser($token->getValue());
  141. if (null === $subparser) {
  142. if (null !== $test) {
  143. $e = new Twig_Error_Syntax(sprintf('Unexpected "%s" tag', $token->getValue()), $token->getLine(), $this->getFilename());
  144. if (is_array($test) && isset($test[0]) && $test[0] instanceof Twig_TokenParserInterface) {
  145. $e->appendMessage(sprintf(' (expecting closing tag for the "%s" tag defined near line %s).', $test[0]->getTag(), $lineno));
  146. }
  147. } else {
  148. $e = new Twig_Error_Syntax(sprintf('Unknown "%s" tag.', $token->getValue()), $token->getLine(), $this->getFilename());
  149. $e->addSuggestions($token->getValue(), array_keys($this->env->getTags()));
  150. }
  151. throw $e;
  152. }
  153. $this->stream->next();
  154. $node = $subparser->parse($token);
  155. if (null !== $node) {
  156. $rv[] = $node;
  157. }
  158. break;
  159. default:
  160. throw new Twig_Error_Syntax('Lexer or parser ended up in unsupported state.', 0, $this->getFilename());
  161. }
  162. }
  163. if (1 === count($rv)) {
  164. return $rv[0];
  165. }
  166. return new Twig_Node($rv, array(), $lineno);
  167. }
  168. public function addHandler($name, $class)
  169. {
  170. $this->handlers[$name] = $class;
  171. }
  172. public function addNodeVisitor(Twig_NodeVisitorInterface $visitor)
  173. {
  174. $this->visitors[] = $visitor;
  175. }
  176. public function getBlockStack()
  177. {
  178. return $this->blockStack;
  179. }
  180. public function peekBlockStack()
  181. {
  182. return $this->blockStack[count($this->blockStack) - 1];
  183. }
  184. public function popBlockStack()
  185. {
  186. array_pop($this->blockStack);
  187. }
  188. public function pushBlockStack($name)
  189. {
  190. $this->blockStack[] = $name;
  191. }
  192. public function hasBlock($name)
  193. {
  194. return isset($this->blocks[$name]);
  195. }
  196. public function getBlock($name)
  197. {
  198. return $this->blocks[$name];
  199. }
  200. public function setBlock($name, Twig_Node_Block $value)
  201. {
  202. $this->blocks[$name] = new Twig_Node_Body(array($value), array(), $value->getLine());
  203. }
  204. public function hasMacro($name)
  205. {
  206. return isset($this->macros[$name]);
  207. }
  208. public function setMacro($name, Twig_Node_Macro $node)
  209. {
  210. if ($this->isReservedMacroName($name)) {
  211. throw new Twig_Error_Syntax(sprintf('"%s" cannot be used as a macro name as it is a reserved keyword.', $name), $node->getLine(), $this->getFilename());
  212. }
  213. $this->macros[$name] = $node;
  214. }
  215. public function isReservedMacroName($name)
  216. {
  217. if (null === $this->reservedMacroNames) {
  218. $this->reservedMacroNames = array();
  219. $r = new ReflectionClass($this->env->getBaseTemplateClass());
  220. foreach ($r->getMethods() as $method) {
  221. $methodName = strtolower($method->getName());
  222. if ('get' === substr($methodName, 0, 3) && isset($methodName[3])) {
  223. $this->reservedMacroNames[] = substr($methodName, 3);
  224. }
  225. }
  226. }
  227. return in_array(strtolower($name), $this->reservedMacroNames);
  228. }
  229. public function addTrait($trait)
  230. {
  231. $this->traits[] = $trait;
  232. }
  233. public function hasTraits()
  234. {
  235. return count($this->traits) > 0;
  236. }
  237. public function embedTemplate(Twig_Node_Module $template)
  238. {
  239. $template->setIndex(mt_rand());
  240. $this->embeddedTemplates[] = $template;
  241. }
  242. public function addImportedSymbol($type, $alias, $name = null, Twig_Node_Expression $node = null)
  243. {
  244. $this->importedSymbols[0][$type][$alias] = array('name' => $name, 'node' => $node);
  245. }
  246. public function getImportedSymbol($type, $alias)
  247. {
  248. foreach ($this->importedSymbols as $functions) {
  249. if (isset($functions[$type][$alias])) {
  250. return $functions[$type][$alias];
  251. }
  252. }
  253. }
  254. public function isMainScope()
  255. {
  256. return 1 === count($this->importedSymbols);
  257. }
  258. public function pushLocalScope()
  259. {
  260. array_unshift($this->importedSymbols, array());
  261. }
  262. public function popLocalScope()
  263. {
  264. array_shift($this->importedSymbols);
  265. }
  266. /**
  267. * Gets the expression parser.
  268. *
  269. * @return Twig_ExpressionParser The expression parser
  270. */
  271. public function getExpressionParser()
  272. {
  273. return $this->expressionParser;
  274. }
  275. public function getParent()
  276. {
  277. return $this->parent;
  278. }
  279. public function setParent($parent)
  280. {
  281. $this->parent = $parent;
  282. }
  283. /**
  284. * Gets the token stream.
  285. *
  286. * @return Twig_TokenStream The token stream
  287. */
  288. public function getStream()
  289. {
  290. return $this->stream;
  291. }
  292. /**
  293. * Gets the current token.
  294. *
  295. * @return Twig_Token The current token
  296. */
  297. public function getCurrentToken()
  298. {
  299. return $this->stream->getCurrent();
  300. }
  301. protected function filterBodyNodes(Twig_NodeInterface $node)
  302. {
  303. // check that the body does not contain non-empty output nodes
  304. if (
  305. ($node instanceof Twig_Node_Text && !ctype_space($node->getAttribute('data')))
  306. ||
  307. (!$node instanceof Twig_Node_Text && !$node instanceof Twig_Node_BlockReference && $node instanceof Twig_NodeOutputInterface)
  308. ) {
  309. if (false !== strpos((string) $node, chr(0xEF).chr(0xBB).chr(0xBF))) {
  310. throw new Twig_Error_Syntax('A template that extends another one cannot have a body but a byte order mark (BOM) has been detected; it must be removed.', $node->getLine(), $this->getFilename());
  311. }
  312. throw new Twig_Error_Syntax('A template that extends another one cannot have a body.', $node->getLine(), $this->getFilename());
  313. }
  314. // bypass "set" nodes as they "capture" the output
  315. if ($node instanceof Twig_Node_Set) {
  316. return $node;
  317. }
  318. if ($node instanceof Twig_NodeOutputInterface) {
  319. return;
  320. }
  321. foreach ($node as $k => $n) {
  322. if (null !== $n && null === $this->filterBodyNodes($n)) {
  323. $node->removeNode($k);
  324. }
  325. }
  326. return $node;
  327. }
  328. }