4 * This file is part of Twig.
6 * (c) 2009 Fabien Potencier
7 * (c) 2009 Armin Ronacher
9 * For the full copyright and license information, please view the LICENSE
10 * file that was distributed with this source code.
14 * Default parser implementation.
16 * @author Fabien Potencier <fabien@symfony.com>
18 class Twig_Parser
implements Twig_ParserInterface
20 protected $stack = array();
25 protected $expressionParser;
27 protected $blockStack;
30 protected $reservedMacroNames;
31 protected $importedSymbols;
33 protected $embeddedTemplates = array();
38 * @param Twig_Environment $env A Twig_Environment instance
40 public function __construct(Twig_Environment
$env)
45 public function getEnvironment()
50 public function getVarName()
52 return sprintf('__internal_%s', hash('sha1', uniqid(mt_rand(), true), false));
55 public function getFilename()
57 return $this->stream
->getFilename();
61 * Converts a token stream to a node tree.
63 * @param Twig_TokenStream $stream A token stream instance
65 * @return Twig_Node_Module A node tree
67 public function parse(Twig_TokenStream
$stream, $test = null, $dropNeedle = false)
69 // push all variables into the stack to keep the current state of the parser
70 $vars = get_object_vars($this);
71 unset($vars['stack'], $vars['env'], $vars['handlers'], $vars['visitors'], $vars['expressionParser']);
72 $this->stack
[] = $vars;
75 if (null === $this->handlers
) {
76 $this->handlers
= $this->env
->getTokenParsers();
77 $this->handlers
->setParser($this);
81 if (null === $this->visitors
) {
82 $this->visitors
= $this->env
->getNodeVisitors();
85 if (null === $this->expressionParser
) {
86 $this->expressionParser
= new Twig_ExpressionParser($this, $this->env
->getUnaryOperators(), $this->env
->getBinaryOperators());
89 $this->stream
= $stream;
91 $this->blocks
= array();
92 $this->macros
= array();
93 $this->traits
= array();
94 $this->blockStack
= array();
95 $this->importedSymbols
= array(array());
96 $this->embeddedTemplates
= array();
99 $body = $this->subparse($test, $dropNeedle);
101 if (null !== $this->parent
) {
102 if (null === $body = $this->filterBodyNodes($body)) {
103 $body = new Twig_Node();
106 } catch (Twig_Error_Syntax
$e) {
107 if (!$e->getTemplateFile()) {
108 $e->setTemplateFile($this->getFilename());
111 if (!$e->getTemplateLine()) {
112 $e->setTemplateLine($this->stream
->getCurrent()->getLine());
118 $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());
120 $traverser = new Twig_NodeTraverser($this->env
, $this->visitors
);
122 $node = $traverser->traverse($node);
124 // restore previous stack so previous parse() call can resume working
125 foreach (array_pop($this->stack
) as $key => $val) {
132 public function subparse($test, $dropNeedle = false)
134 $lineno = $this->getCurrentToken()->getLine();
136 while (!$this->stream
->isEOF()) {
137 switch ($this->getCurrentToken()->getType()) {
138 case Twig_Token
::TEXT_TYPE
:
139 $token = $this->stream
->next();
140 $rv[] = new Twig_Node_Text($token->getValue(), $token->getLine());
143 case Twig_Token
::VAR_START_TYPE
:
144 $token = $this->stream
->next();
145 $expr = $this->expressionParser
->parseExpression();
146 $this->stream
->expect(Twig_Token
::VAR_END_TYPE
);
147 $rv[] = new Twig_Node_Print($expr, $token->getLine());
150 case Twig_Token
::BLOCK_START_TYPE
:
151 $this->stream
->next();
152 $token = $this->getCurrentToken();
154 if ($token->getType() !== Twig_Token
::NAME_TYPE
) {
155 throw new Twig_Error_Syntax('A block must start with a tag name', $token->getLine(), $this->getFilename());
158 if (null !== $test && call_user_func($test, $token)) {
160 $this->stream
->next();
163 if (1 === count($rv)) {
167 return new Twig_Node($rv, array(), $lineno);
170 $subparser = $this->handlers
->getTokenParser($token->getValue());
171 if (null === $subparser) {
172 if (null !== $test) {
173 $error = sprintf('Unexpected tag name "%s"', $token->getValue());
174 if (is_array($test) && isset($test[0]) && $test[0] instanceof Twig_TokenParserInterface
) {
175 $error .= sprintf(' (expecting closing tag for the "%s" tag defined near line %s)', $test[0]->getTag(), $lineno);
178 throw new Twig_Error_Syntax($error, $token->getLine(), $this->getFilename());
181 $message = sprintf('Unknown tag name "%s"', $token->getValue());
182 if ($alternatives = $this->env
->computeAlternatives($token->getValue(), array_keys($this->env
->getTags()))) {
183 $message = sprintf('%s. Did you mean "%s"', $message, implode('", "', $alternatives));
186 throw new Twig_Error_Syntax($message, $token->getLine(), $this->getFilename());
189 $this->stream
->next();
191 $node = $subparser->parse($token);
192 if (null !== $node) {
198 throw new Twig_Error_Syntax('Lexer or parser ended up in unsupported state.', 0, $this->getFilename());
202 if (1 === count($rv)) {
206 return new Twig_Node($rv, array(), $lineno);
209 public function addHandler($name, $class)
211 $this->handlers
[$name] = $class;
214 public function addNodeVisitor(Twig_NodeVisitorInterface
$visitor)
216 $this->visitors
[] = $visitor;
219 public function getBlockStack()
221 return $this->blockStack
;
224 public function peekBlockStack()
226 return $this->blockStack
[count($this->blockStack
) - 1];
229 public function popBlockStack()
231 array_pop($this->blockStack
);
234 public function pushBlockStack($name)
236 $this->blockStack
[] = $name;
239 public function hasBlock($name)
241 return isset($this->blocks
[$name]);
244 public function getBlock($name)
246 return $this->blocks
[$name];
249 public function setBlock($name, $value)
251 $this->blocks
[$name] = new Twig_Node_Body(array($value), array(), $value->getLine());
254 public function hasMacro($name)
256 return isset($this->macros
[$name]);
259 public function setMacro($name, Twig_Node_Macro
$node)
261 if (null === $this->reservedMacroNames
) {
262 $this->reservedMacroNames
= array();
263 $r = new ReflectionClass($this->env
->getBaseTemplateClass());
264 foreach ($r->getMethods() as $method) {
265 $this->reservedMacroNames
[] = $method->getName();
269 if (in_array($name, $this->reservedMacroNames
)) {
270 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());
273 $this->macros
[$name] = $node;
276 public function addTrait($trait)
278 $this->traits
[] = $trait;
281 public function hasTraits()
283 return count($this->traits
) > 0;
286 public function embedTemplate(Twig_Node_Module
$template)
288 $template->setIndex(mt_rand());
290 $this->embeddedTemplates
[] = $template;
293 public function addImportedSymbol($type, $alias, $name = null, Twig_Node_Expression
$node = null)
295 $this->importedSymbols
[0][$type][$alias] = array('name' => $name, 'node' => $node);
298 public function getImportedSymbol($type, $alias)
300 foreach ($this->importedSymbols
as $functions) {
301 if (isset($functions[$type][$alias])) {
302 return $functions[$type][$alias];
307 public function isMainScope()
309 return 1 === count($this->importedSymbols
);
312 public function pushLocalScope()
314 array_unshift($this->importedSymbols
, array());
317 public function popLocalScope()
319 array_shift($this->importedSymbols
);
323 * Gets the expression parser.
325 * @return Twig_ExpressionParser The expression parser
327 public function getExpressionParser()
329 return $this->expressionParser
;
332 public function getParent()
334 return $this->parent
;
337 public function setParent($parent)
339 $this->parent
= $parent;
343 * Gets the token stream.
345 * @return Twig_TokenStream The token stream
347 public function getStream()
349 return $this->stream
;
353 * Gets the current token.
355 * @return Twig_Token The current token
357 public function getCurrentToken()
359 return $this->stream
->getCurrent();
362 protected function filterBodyNodes(Twig_NodeInterface
$node)
364 // check that the body does not contain non-empty output nodes
366 ($node instanceof Twig_Node_Text
&& !ctype_space($node->getAttribute('data')))
368 (!$node instanceof Twig_Node_Text
&& !$node instanceof Twig_Node_BlockReference
&& $node instanceof Twig_NodeOutputInterface
)
370 if (false !== strpos((string) $node, chr(0xEF).chr(0xBB).chr(0xBF))) {
371 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());
374 throw new Twig_Error_Syntax('A template that extends another one cannot have a body.', $node->getLine(), $this->getFilename());
377 // bypass "set" nodes as they "capture" the output
378 if ($node instanceof Twig_Node_Set
) {
382 if ($node instanceof Twig_NodeOutputInterface
) {
386 foreach ($node as $k => $n) {
387 if (null !== $n && null === $n = $this->filterBodyNodes($n)) {
388 $node->removeNode($k);