Parser.php 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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 $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 $importedFunctions;
  30. protected $tmpVarCount;
  31. protected $traits;
  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_%d', substr($this->env->getTemplateClass($this->stream->getFilename()), strlen($this->env->getTemplateClassPrefix())), ++$this->tmpVarCount);
  48. }
  49. /**
  50. * Converts a token stream to a node tree.
  51. *
  52. * @param Twig_TokenStream $stream A token stream instance
  53. *
  54. * @return Twig_Node_Module A node tree
  55. */
  56. public function parse(Twig_TokenStream $stream)
  57. {
  58. $this->tmpVarCount = 0;
  59. // tag handlers
  60. $this->handlers = $this->env->getTokenParsers();
  61. $this->handlers->setParser($this);
  62. // node visitors
  63. $this->visitors = $this->env->getNodeVisitors();
  64. if (null === $this->expressionParser) {
  65. $this->expressionParser = new Twig_ExpressionParser($this, $this->env->getUnaryOperators(), $this->env->getBinaryOperators());
  66. }
  67. $this->stream = $stream;
  68. $this->parent = null;
  69. $this->blocks = array();
  70. $this->macros = array();
  71. $this->traits = array();
  72. $this->blockStack = array();
  73. $this->importedFunctions = array(array());
  74. try {
  75. $body = $this->subparse(null);
  76. if (null !== $this->parent) {
  77. if (null === $body = $this->filterBodyNodes($body)) {
  78. $body = new Twig_Node();
  79. }
  80. }
  81. } catch (Twig_Error_Syntax $e) {
  82. if (null === $e->getTemplateFile()) {
  83. $e->setTemplateFile($this->stream->getFilename());
  84. }
  85. throw $e;
  86. }
  87. $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->stream->getFilename());
  88. $traverser = new Twig_NodeTraverser($this->env, $this->visitors);
  89. return $traverser->traverse($node);
  90. }
  91. public function subparse($test, $dropNeedle = false)
  92. {
  93. $lineno = $this->getCurrentToken()->getLine();
  94. $rv = array();
  95. while (!$this->stream->isEOF()) {
  96. switch ($this->getCurrentToken()->getType()) {
  97. case Twig_Token::TEXT_TYPE:
  98. $token = $this->stream->next();
  99. $rv[] = new Twig_Node_Text($token->getValue(), $token->getLine());
  100. break;
  101. case Twig_Token::VAR_START_TYPE:
  102. $token = $this->stream->next();
  103. $expr = $this->expressionParser->parseExpression();
  104. $this->stream->expect(Twig_Token::VAR_END_TYPE);
  105. $rv[] = new Twig_Node_Print($expr, $token->getLine());
  106. break;
  107. case Twig_Token::BLOCK_START_TYPE:
  108. $this->stream->next();
  109. $token = $this->getCurrentToken();
  110. if ($token->getType() !== Twig_Token::NAME_TYPE) {
  111. throw new Twig_Error_Syntax('A block must start with a tag name', $token->getLine(), $this->stream->getFilename());
  112. }
  113. if (null !== $test && call_user_func($test, $token)) {
  114. if ($dropNeedle) {
  115. $this->stream->next();
  116. }
  117. if (1 === count($rv)) {
  118. return $rv[0];
  119. }
  120. return new Twig_Node($rv, array(), $lineno);
  121. }
  122. $subparser = $this->handlers->getTokenParser($token->getValue());
  123. if (null === $subparser) {
  124. if (null !== $test) {
  125. throw new Twig_Error_Syntax(sprintf('Unexpected tag name "%s" (expecting closing tag for the "%s" tag defined near line %s)', $token->getValue(), $test[0]->getTag(), $lineno), $token->getLine(), $this->stream->getFilename());
  126. }
  127. throw new Twig_Error_Syntax(sprintf('Unknown tag name "%s"', $token->getValue()), $token->getLine(), $this->stream->getFilename());
  128. }
  129. $this->stream->next();
  130. $node = $subparser->parse($token);
  131. if (null !== $node) {
  132. $rv[] = $node;
  133. }
  134. break;
  135. default:
  136. throw new Twig_Error_Syntax('Lexer or parser ended up in unsupported state.', -1, $this->stream->getFilename());
  137. }
  138. }
  139. if (1 === count($rv)) {
  140. return $rv[0];
  141. }
  142. return new Twig_Node($rv, array(), $lineno);
  143. }
  144. public function addHandler($name, $class)
  145. {
  146. $this->handlers[$name] = $class;
  147. }
  148. public function addNodeVisitor(Twig_NodeVisitorInterface $visitor)
  149. {
  150. $this->visitors[] = $visitor;
  151. }
  152. public function getBlockStack()
  153. {
  154. return $this->blockStack;
  155. }
  156. public function peekBlockStack()
  157. {
  158. return $this->blockStack[count($this->blockStack) - 1];
  159. }
  160. public function popBlockStack()
  161. {
  162. array_pop($this->blockStack);
  163. }
  164. public function pushBlockStack($name)
  165. {
  166. $this->blockStack[] = $name;
  167. }
  168. public function hasBlock($name)
  169. {
  170. return isset($this->blocks[$name]);
  171. }
  172. public function setBlock($name, $value)
  173. {
  174. $this->blocks[$name] = new Twig_Node_Body(array($value));
  175. }
  176. public function hasMacro($name)
  177. {
  178. return isset($this->macros[$name]);
  179. }
  180. public function setMacro($name, Twig_Node_Macro $node)
  181. {
  182. if (null === $this->reservedMacroNames) {
  183. $this->reservedMacroNames = array();
  184. $r = new ReflectionClass($this->env->getBaseTemplateClass());
  185. foreach ($r->getMethods() as $method) {
  186. $this->reservedMacroNames[] = $method->getName();
  187. }
  188. }
  189. if (in_array($name, $this->reservedMacroNames)) {
  190. throw new Twig_Error_Syntax(sprintf('"%s" cannot be used as a macro name as it is a reserved keyword', $name), $node->getLine());
  191. }
  192. $this->macros[$name] = $node;
  193. }
  194. public function addTrait($trait)
  195. {
  196. $this->traits[] = $trait;
  197. }
  198. public function hasTraits()
  199. {
  200. return count($this->traits) > 0;
  201. }
  202. public function addImportedFunction($alias, $name, Twig_Node_Expression $node)
  203. {
  204. $this->importedFunctions[0][$alias] = array('name' => $name, 'node' => $node);
  205. }
  206. public function getImportedFunction($alias)
  207. {
  208. foreach ($this->importedFunctions as $functions) {
  209. if (isset($functions[$alias])) {
  210. return $functions[$alias];
  211. }
  212. }
  213. }
  214. public function isMainScope()
  215. {
  216. return 1 === count($this->importedFunctions);
  217. }
  218. public function pushLocalScope()
  219. {
  220. array_unshift($this->importedFunctions, array());
  221. }
  222. public function popLocalScope()
  223. {
  224. array_shift($this->importedFunctions);
  225. }
  226. /**
  227. * Gets the expression parser.
  228. *
  229. * @return Twig_ExpressionParser The expression parser
  230. */
  231. public function getExpressionParser()
  232. {
  233. return $this->expressionParser;
  234. }
  235. public function getParent()
  236. {
  237. return $this->parent;
  238. }
  239. public function setParent($parent)
  240. {
  241. $this->parent = $parent;
  242. }
  243. /**
  244. * Gets the token stream.
  245. *
  246. * @return Twig_TokenStream The token stream
  247. */
  248. public function getStream()
  249. {
  250. return $this->stream;
  251. }
  252. /**
  253. * Gets the current token.
  254. *
  255. * @return Twig_Token The current token
  256. */
  257. public function getCurrentToken()
  258. {
  259. return $this->stream->getCurrent();
  260. }
  261. protected function filterBodyNodes(Twig_NodeInterface $node)
  262. {
  263. // check that the body does not contain non-empty output nodes
  264. if (
  265. ($node instanceof Twig_Node_Text && !ctype_space($node->getAttribute('data')))
  266. ||
  267. (!$node instanceof Twig_Node_Text && !$node instanceof Twig_Node_BlockReference && $node instanceof Twig_NodeOutputInterface)
  268. ) {
  269. if (false !== strpos((string) $node, chr(0xEF).chr(0xBB).chr(0xBF))) {
  270. 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());
  271. } else {
  272. throw new Twig_Error_Syntax('A template that extends another one cannot have a body.', $node->getLine(), $this->stream->getFilename());
  273. }
  274. }
  275. // bypass "set" nodes as they "capture" the output
  276. if ($node instanceof Twig_Node_Set) {
  277. return $node;
  278. }
  279. if ($node instanceof Twig_NodeOutputInterface) {
  280. return;
  281. }
  282. foreach ($node as $k => $n) {
  283. if (null !== $n && null === $n = $this->filterBodyNodes($n)) {
  284. $node->removeNode($k);
  285. }
  286. }
  287. return $node;
  288. }
  289. }