Parser.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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 $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->importedFunctions = 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. 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 getBlock($name)
  191. {
  192. return $this->blocks[$name];
  193. }
  194. public function setBlock($name, $value)
  195. {
  196. $this->blocks[$name] = new Twig_Node_Body(array($value), array(), $value->getLine());
  197. }
  198. public function hasMacro($name)
  199. {
  200. return isset($this->macros[$name]);
  201. }
  202. public function setMacro($name, Twig_Node_Macro $node)
  203. {
  204. if (null === $this->reservedMacroNames) {
  205. $this->reservedMacroNames = array();
  206. $r = new ReflectionClass($this->env->getBaseTemplateClass());
  207. foreach ($r->getMethods() as $method) {
  208. $this->reservedMacroNames[] = $method->getName();
  209. }
  210. }
  211. if (in_array($name, $this->reservedMacroNames)) {
  212. throw new Twig_Error_Syntax(sprintf('"%s" cannot be used as a macro name as it is a reserved keyword', $name), $node->getLine());
  213. }
  214. $this->macros[$name] = $node;
  215. }
  216. public function addTrait($trait)
  217. {
  218. $this->traits[] = $trait;
  219. }
  220. public function hasTraits()
  221. {
  222. return count($this->traits) > 0;
  223. }
  224. public function embedTemplate(Twig_Node_Module $template)
  225. {
  226. $template->setIndex(mt_rand());
  227. $this->embeddedTemplates[] = $template;
  228. }
  229. public function addImportedFunction($alias, $name, Twig_Node_Expression $node)
  230. {
  231. $this->importedFunctions[0][$alias] = array('name' => $name, 'node' => $node);
  232. }
  233. public function getImportedFunction($alias)
  234. {
  235. foreach ($this->importedFunctions as $functions) {
  236. if (isset($functions[$alias])) {
  237. return $functions[$alias];
  238. }
  239. }
  240. }
  241. public function isMainScope()
  242. {
  243. return 1 === count($this->importedFunctions);
  244. }
  245. public function pushLocalScope()
  246. {
  247. array_unshift($this->importedFunctions, array());
  248. }
  249. public function popLocalScope()
  250. {
  251. array_shift($this->importedFunctions);
  252. }
  253. /**
  254. * Gets the expression parser.
  255. *
  256. * @return Twig_ExpressionParser The expression parser
  257. */
  258. public function getExpressionParser()
  259. {
  260. return $this->expressionParser;
  261. }
  262. public function getParent()
  263. {
  264. return $this->parent;
  265. }
  266. public function setParent($parent)
  267. {
  268. $this->parent = $parent;
  269. }
  270. /**
  271. * Gets the token stream.
  272. *
  273. * @return Twig_TokenStream The token stream
  274. */
  275. public function getStream()
  276. {
  277. return $this->stream;
  278. }
  279. /**
  280. * Gets the current token.
  281. *
  282. * @return Twig_Token The current token
  283. */
  284. public function getCurrentToken()
  285. {
  286. return $this->stream->getCurrent();
  287. }
  288. protected function filterBodyNodes(Twig_NodeInterface $node)
  289. {
  290. // check that the body does not contain non-empty output nodes
  291. if (
  292. ($node instanceof Twig_Node_Text && !ctype_space($node->getAttribute('data')))
  293. ||
  294. (!$node instanceof Twig_Node_Text && !$node instanceof Twig_Node_BlockReference && $node instanceof Twig_NodeOutputInterface)
  295. ) {
  296. if (false !== strpos((string) $node, chr(0xEF).chr(0xBB).chr(0xBF))) {
  297. 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());
  298. }
  299. throw new Twig_Error_Syntax('A template that extends another one cannot have a body.', $node->getLine(), $this->stream->getFilename());
  300. }
  301. // bypass "set" nodes as they "capture" the output
  302. if ($node instanceof Twig_Node_Set) {
  303. return $node;
  304. }
  305. if ($node instanceof Twig_NodeOutputInterface) {
  306. return;
  307. }
  308. foreach ($node as $k => $n) {
  309. if (null !== $n && null === $n = $this->filterBodyNodes($n)) {
  310. $node->removeNode($k);
  311. }
  312. }
  313. return $node;
  314. }
  315. }