4 * This file is part of Twig.
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();
34 private $varNameSalt = 0;
36 public function __construct(Twig_Environment
$env)
42 * @deprecated since 1.27 (to be removed in 2.0)
44 public function getEnvironment()
46 @trigger_error
('The '.__METHOD__
.' method is deprecated since version 1.27 and will be removed in 2.0.', E_USER_DEPRECATED
);
51 public function getVarName()
53 return sprintf('__internal_%s', hash('sha256', __METHOD__
.$this->stream
->getSourceContext()->getCode().$this->varNameSalt++
));
57 * @deprecated since 1.27 (to be removed in 2.0). Use $parser->getStream()->getSourceContext()->getPath() instead.
59 public function getFilename()
61 @trigger_error
(sprintf('The "%s" method is deprecated since version 1.27 and will be removed in 2.0. Use $parser->getStream()->getSourceContext()->getPath() instead.', __METHOD__
), E_USER_DEPRECATED
);
63 return $this->stream
->getSourceContext()->getName();
66 public function parse(Twig_TokenStream
$stream, $test = null, $dropNeedle = false)
68 // push all variables into the stack to keep the current state of the parser
69 // using get_object_vars() instead of foreach would lead to https://bugs.php.net/71336
70 // This hack can be removed when min version if PHP 7.0
72 foreach ($this as $k => $v) {
76 unset($vars['stack'], $vars['env'], $vars['handlers'], $vars['visitors'], $vars['expressionParser'], $vars['reservedMacroNames']);
77 $this->stack
[] = $vars;
80 if (null === $this->handlers
) {
81 $this->handlers
= $this->env
->getTokenParsers();
82 $this->handlers
->setParser($this);
86 if (null === $this->visitors
) {
87 $this->visitors
= $this->env
->getNodeVisitors();
90 if (null === $this->expressionParser
) {
91 $this->expressionParser
= new Twig_ExpressionParser($this, $this->env
);
94 $this->stream
= $stream;
96 $this->blocks
= array();
97 $this->macros
= array();
98 $this->traits
= array();
99 $this->blockStack
= array();
100 $this->importedSymbols
= array(array());
101 $this->embeddedTemplates
= array();
102 $this->varNameSalt
= 0;
105 $body = $this->subparse($test, $dropNeedle);
107 if (null !== $this->parent
&& null === $body = $this->filterBodyNodes($body)) {
108 $body = new Twig_Node();
110 } catch (Twig_Error_Syntax
$e) {
111 if (!$e->getSourceContext()) {
112 $e->setSourceContext($this->stream
->getSourceContext());
115 if (!$e->getTemplateLine()) {
116 $e->setTemplateLine($this->stream
->getCurrent()->getLine());
122 $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
, $stream->getSourceContext());
124 $traverser = new Twig_NodeTraverser($this->env
, $this->visitors
);
126 $node = $traverser->traverse($node);
128 // restore previous stack so previous parse() call can resume working
129 foreach (array_pop($this->stack
) as $key => $val) {
136 public function subparse($test, $dropNeedle = false)
138 $lineno = $this->getCurrentToken()->getLine();
140 while (!$this->stream
->isEOF()) {
141 switch ($this->getCurrentToken()->getType()) {
142 case Twig_Token
::TEXT_TYPE
:
143 $token = $this->stream
->next();
144 $rv[] = new Twig_Node_Text($token->getValue(), $token->getLine());
147 case Twig_Token
::VAR_START_TYPE
:
148 $token = $this->stream
->next();
149 $expr = $this->expressionParser
->parseExpression();
150 $this->stream
->expect(Twig_Token
::VAR_END_TYPE
);
151 $rv[] = new Twig_Node_Print($expr, $token->getLine());
154 case Twig_Token
::BLOCK_START_TYPE
:
155 $this->stream
->next();
156 $token = $this->getCurrentToken();
158 if (Twig_Token
::NAME_TYPE
!== $token->getType()) {
159 throw new Twig_Error_Syntax('A block must start with a tag name.', $token->getLine(), $this->stream
->getSourceContext());
162 if (null !== $test && call_user_func($test, $token)) {
164 $this->stream
->next();
167 if (1 === count($rv)) {
171 return new Twig_Node($rv, array(), $lineno);
174 $subparser = $this->handlers
->getTokenParser($token->getValue());
175 if (null === $subparser) {
176 if (null !== $test) {
177 $e = new Twig_Error_Syntax(sprintf('Unexpected "%s" tag', $token->getValue()), $token->getLine(), $this->stream
->getSourceContext());
179 if (is_array($test) && isset($test[0]) && $test[0] instanceof Twig_TokenParserInterface
) {
180 $e->appendMessage(sprintf(' (expecting closing tag for the "%s" tag defined near line %s).', $test[0]->getTag(), $lineno));
183 $e = new Twig_Error_Syntax(sprintf('Unknown "%s" tag.', $token->getValue()), $token->getLine(), $this->stream
->getSourceContext());
184 $e->addSuggestions($token->getValue(), array_keys($this->env
->getTags()));
190 $this->stream
->next();
192 $node = $subparser->parse($token);
193 if (null !== $node) {
199 throw new Twig_Error_Syntax('Lexer or parser ended up in unsupported state.', $this->getCurrentToken()->getLine(), $this->stream
->getSourceContext());
203 if (1 === count($rv)) {
207 return new Twig_Node($rv, array(), $lineno);
211 * @deprecated since 1.27 (to be removed in 2.0)
213 public function addHandler($name, $class)
215 @trigger_error
('The '.__METHOD__
.' method is deprecated since version 1.27 and will be removed in 2.0.', E_USER_DEPRECATED
);
217 $this->handlers
[$name] = $class;
221 * @deprecated since 1.27 (to be removed in 2.0)
223 public function addNodeVisitor(Twig_NodeVisitorInterface
$visitor)
225 @trigger_error
('The '.__METHOD__
.' method is deprecated since version 1.27 and will be removed in 2.0.', E_USER_DEPRECATED
);
227 $this->visitors
[] = $visitor;
230 public function getBlockStack()
232 return $this->blockStack
;
235 public function peekBlockStack()
237 return $this->blockStack
[count($this->blockStack
) - 1];
240 public function popBlockStack()
242 array_pop($this->blockStack
);
245 public function pushBlockStack($name)
247 $this->blockStack
[] = $name;
250 public function hasBlock($name)
252 return isset($this->blocks
[$name]);
255 public function getBlock($name)
257 return $this->blocks
[$name];
260 public function setBlock($name, Twig_Node_Block
$value)
262 $this->blocks
[$name] = new Twig_Node_Body(array($value), array(), $value->getTemplateLine());
265 public function hasMacro($name)
267 return isset($this->macros
[$name]);
270 public function setMacro($name, Twig_Node_Macro
$node)
272 if ($this->isReservedMacroName($name)) {
273 throw new Twig_Error_Syntax(sprintf('"%s" cannot be used as a macro name as it is a reserved keyword.', $name), $node->getTemplateLine(), $this->stream
->getSourceContext());
276 $this->macros
[$name] = $node;
279 public function isReservedMacroName($name)
281 if (null === $this->reservedMacroNames
) {
282 $this->reservedMacroNames
= array();
283 $r = new ReflectionClass($this->env
->getBaseTemplateClass());
284 foreach ($r->getMethods() as $method) {
285 $methodName = strtolower($method->getName());
287 if ('get' === substr($methodName, 0, 3) && isset($methodName[3])) {
288 $this->reservedMacroNames
[] = substr($methodName, 3);
293 return in_array(strtolower($name), $this->reservedMacroNames
);
296 public function addTrait($trait)
298 $this->traits
[] = $trait;
301 public function hasTraits()
303 return count($this->traits
) > 0;
306 public function embedTemplate(Twig_Node_Module
$template)
308 $template->setIndex(mt_rand());
310 $this->embeddedTemplates
[] = $template;
313 public function addImportedSymbol($type, $alias, $name = null, Twig_Node_Expression
$node = null)
315 $this->importedSymbols
[0][$type][$alias] = array('name' => $name, 'node' => $node);
318 public function getImportedSymbol($type, $alias)
320 foreach ($this->importedSymbols
as $functions) {
321 if (isset($functions[$type][$alias])) {
322 return $functions[$type][$alias];
327 public function isMainScope()
329 return 1 === count($this->importedSymbols
);
332 public function pushLocalScope()
334 array_unshift($this->importedSymbols
, array());
337 public function popLocalScope()
339 array_shift($this->importedSymbols
);
343 * @return Twig_ExpressionParser
345 public function getExpressionParser()
347 return $this->expressionParser
;
350 public function getParent()
352 return $this->parent
;
355 public function setParent($parent)
357 $this->parent
= $parent;
361 * @return Twig_TokenStream
363 public function getStream()
365 return $this->stream
;
371 public function getCurrentToken()
373 return $this->stream
->getCurrent();
376 protected function filterBodyNodes(Twig_NodeInterface
$node)
378 // check that the body does not contain non-empty output nodes
380 ($node instanceof Twig_Node_Text
&& !ctype_space($node->getAttribute('data')))
382 (!$node instanceof Twig_Node_Text
&& !$node instanceof Twig_Node_BlockReference
&& $node instanceof Twig_NodeOutputInterface
)
384 if (false !== strpos((string) $node, chr(0xEF).chr(0xBB).chr(0xBF))) {
385 throw new Twig_Error_Syntax('A template that extends another one cannot start with a byte order mark (BOM); it must be removed.', $node->getTemplateLine(), $this->stream
->getSourceContext());
388 throw new Twig_Error_Syntax('A template that extends another one cannot include content outside Twig blocks. Did you forget to put the content inside a {% block %} tag?', $node->getTemplateLine(), $this->stream
->getSourceContext());
391 // bypass nodes that will "capture" the output
392 if ($node instanceof Twig_NodeCaptureInterface
) {
396 if ($node instanceof Twig_NodeOutputInterface
) {
400 foreach ($node as $k => $n) {
401 if (null !== $n && null === $this->filterBodyNodes($n)) {
402 $node->removeNode($k);
410 class_alias('Twig_Parser', 'Twig\Parser', false);
411 class_exists('Twig_Node');
412 class_exists('Twig_TokenStream');