Parser.php 11KB

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