Parser.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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 $importedFunctions;
  31. protected $tmpVarCount;
  32. protected $traits;
  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_%d', substr($this->env->getTemplateClass($this->stream->getFilename()), strlen($this->env->getTemplateClassPrefix())), ++$this->tmpVarCount);
  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)
  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. $this->tmpVarCount = 0;
  64. // tag handlers
  65. if (null === $this->handlers) {
  66. $this->handlers = $this->env->getTokenParsers();
  67. $this->handlers->setParser($this);
  68. }
  69. // node visitors
  70. if (null === $this->visitors) {
  71. $this->visitors = $this->env->getNodeVisitors();
  72. }
  73. if (null === $this->expressionParser) {
  74. $this->expressionParser = new Twig_ExpressionParser($this, $this->env->getUnaryOperators(), $this->env->getBinaryOperators());
  75. }
  76. $this->stream = $stream;
  77. $this->parent = null;
  78. $this->blocks = array();
  79. $this->macros = array();
  80. $this->traits = array();
  81. $this->blockStack = array();
  82. $this->importedFunctions = array(array());
  83. try {
  84. $body = $this->subparse(null);
  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->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. 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());
  140. }
  141. $message = sprintf('Unknown tag name "%s"', $token->getValue());
  142. if ($alternatives = $this->env->computeAlternatives($token->getValue(), array_keys($this->env->getTags()))) {
  143. $message = sprintf('%s. Did you mean "%s"', $message, implode('", "', $alternatives));
  144. }
  145. throw new Twig_Error_Syntax($message, $token->getLine(), $this->stream->getFilename());
  146. }
  147. $this->stream->next();
  148. $node = $subparser->parse($token);
  149. if (null !== $node) {
  150. $rv[] = $node;
  151. }
  152. break;
  153. default:
  154. throw new Twig_Error_Syntax('Lexer or parser ended up in unsupported state.', -1, $this->stream->getFilename());
  155. }
  156. }
  157. if (1 === count($rv)) {
  158. return $rv[0];
  159. }
  160. return new Twig_Node($rv, array(), $lineno);
  161. }
  162. public function addHandler($name, $class)
  163. {
  164. $this->handlers[$name] = $class;
  165. }
  166. public function addNodeVisitor(Twig_NodeVisitorInterface $visitor)
  167. {
  168. $this->visitors[] = $visitor;
  169. }
  170. public function getBlockStack()
  171. {
  172. return $this->blockStack;
  173. }
  174. public function peekBlockStack()
  175. {
  176. return $this->blockStack[count($this->blockStack) - 1];
  177. }
  178. public function popBlockStack()
  179. {
  180. array_pop($this->blockStack);
  181. }
  182. public function pushBlockStack($name)
  183. {
  184. $this->blockStack[] = $name;
  185. }
  186. public function hasBlock($name)
  187. {
  188. return isset($this->blocks[$name]);
  189. }
  190. public function setBlock($name, $value)
  191. {
  192. $this->blocks[$name] = new Twig_Node_Body(array($value));
  193. }
  194. public function hasMacro($name)
  195. {
  196. return isset($this->macros[$name]);
  197. }
  198. public function setMacro($name, Twig_Node_Macro $node)
  199. {
  200. if (null === $this->reservedMacroNames) {
  201. $this->reservedMacroNames = array();
  202. $r = new ReflectionClass($this->env->getBaseTemplateClass());
  203. foreach ($r->getMethods() as $method) {
  204. $this->reservedMacroNames[] = $method->getName();
  205. }
  206. }
  207. if (in_array($name, $this->reservedMacroNames)) {
  208. throw new Twig_Error_Syntax(sprintf('"%s" cannot be used as a macro name as it is a reserved keyword', $name), $node->getLine());
  209. }
  210. $this->macros[$name] = $node;
  211. }
  212. public function addTrait($trait)
  213. {
  214. $this->traits[] = $trait;
  215. }
  216. public function hasTraits()
  217. {
  218. return count($this->traits) > 0;
  219. }
  220. public function addImportedFunction($alias, $name, Twig_Node_Expression $node)
  221. {
  222. $this->importedFunctions[0][$alias] = array('name' => $name, 'node' => $node);
  223. }
  224. public function getImportedFunction($alias)
  225. {
  226. foreach ($this->importedFunctions as $functions) {
  227. if (isset($functions[$alias])) {
  228. return $functions[$alias];
  229. }
  230. }
  231. }
  232. public function isMainScope()
  233. {
  234. return 1 === count($this->importedFunctions);
  235. }
  236. public function pushLocalScope()
  237. {
  238. array_unshift($this->importedFunctions, array());
  239. }
  240. public function popLocalScope()
  241. {
  242. array_shift($this->importedFunctions);
  243. }
  244. /**
  245. * Gets the expression parser.
  246. *
  247. * @return Twig_ExpressionParser The expression parser
  248. */
  249. public function getExpressionParser()
  250. {
  251. return $this->expressionParser;
  252. }
  253. public function getParent()
  254. {
  255. return $this->parent;
  256. }
  257. public function setParent($parent)
  258. {
  259. $this->parent = $parent;
  260. }
  261. /**
  262. * Gets the token stream.
  263. *
  264. * @return Twig_TokenStream The token stream
  265. */
  266. public function getStream()
  267. {
  268. return $this->stream;
  269. }
  270. /**
  271. * Gets the current token.
  272. *
  273. * @return Twig_Token The current token
  274. */
  275. public function getCurrentToken()
  276. {
  277. return $this->stream->getCurrent();
  278. }
  279. protected function filterBodyNodes(Twig_NodeInterface $node)
  280. {
  281. // check that the body does not contain non-empty output nodes
  282. if (
  283. ($node instanceof Twig_Node_Text && !ctype_space($node->getAttribute('data')))
  284. ||
  285. (!$node instanceof Twig_Node_Text && !$node instanceof Twig_Node_BlockReference && $node instanceof Twig_NodeOutputInterface)
  286. ) {
  287. if (false !== strpos((string) $node, chr(0xEF).chr(0xBB).chr(0xBF))) {
  288. 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());
  289. } else {
  290. throw new Twig_Error_Syntax('A template that extends another one cannot have a body.', $node->getLine(), $this->stream->getFilename());
  291. }
  292. }
  293. // bypass "set" nodes as they "capture" the output
  294. if ($node instanceof Twig_Node_Set) {
  295. return $node;
  296. }
  297. if ($node instanceof Twig_NodeOutputInterface) {
  298. return;
  299. }
  300. foreach ($node as $k => $n) {
  301. if (null !== $n && null === $n = $this->filterBodyNodes($n)) {
  302. $node->removeNode($k);
  303. }
  304. }
  305. return $node;
  306. }
  307. }