blob: 4428208fed3214b861ddbce482ea2b806528bcec [file] [log] [blame]
Matthias Andreas Benkard12a57352021-12-28 18:02:04 +01001<?php
2
3/*
4 * This file is part of Twig.
5 *
6 * (c) Fabien Potencier
7 * (c) Armin Ronacher
8 *
9 * For the full copyright and license information, please view the LICENSE
10 * file that was distributed with this source code.
11 */
12
13namespace Twig;
14
15use Twig\Error\SyntaxError;
16use Twig\Node\BlockNode;
17use Twig\Node\BlockReferenceNode;
18use Twig\Node\BodyNode;
19use Twig\Node\Expression\AbstractExpression;
20use Twig\Node\MacroNode;
21use Twig\Node\ModuleNode;
22use Twig\Node\Node;
23use Twig\Node\NodeCaptureInterface;
24use Twig\Node\NodeOutputInterface;
25use Twig\Node\PrintNode;
26use Twig\Node\TextNode;
27use Twig\TokenParser\TokenParserInterface;
28
29/**
30 * @author Fabien Potencier <fabien@symfony.com>
31 */
32class Parser
33{
34 private $stack = [];
35 private $stream;
36 private $parent;
37 private $visitors;
38 private $expressionParser;
39 private $blocks;
40 private $blockStack;
41 private $macros;
42 private $env;
43 private $importedSymbols;
44 private $traits;
45 private $embeddedTemplates = [];
46 private $varNameSalt = 0;
47
48 public function __construct(Environment $env)
49 {
50 $this->env = $env;
51 }
52
53 public function getVarName(): string
54 {
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +010055 return sprintf('__internal_parse_%d', $this->varNameSalt++);
Matthias Andreas Benkard12a57352021-12-28 18:02:04 +010056 }
57
58 public function parse(TokenStream $stream, $test = null, bool $dropNeedle = false): ModuleNode
59 {
60 $vars = get_object_vars($this);
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +010061 unset($vars['stack'], $vars['env'], $vars['handlers'], $vars['visitors'], $vars['expressionParser'], $vars['reservedMacroNames'], $vars['varNameSalt']);
Matthias Andreas Benkard12a57352021-12-28 18:02:04 +010062 $this->stack[] = $vars;
63
64 // node visitors
65 if (null === $this->visitors) {
66 $this->visitors = $this->env->getNodeVisitors();
67 }
68
69 if (null === $this->expressionParser) {
70 $this->expressionParser = new ExpressionParser($this, $this->env);
71 }
72
73 $this->stream = $stream;
74 $this->parent = null;
75 $this->blocks = [];
76 $this->macros = [];
77 $this->traits = [];
78 $this->blockStack = [];
79 $this->importedSymbols = [[]];
80 $this->embeddedTemplates = [];
Matthias Andreas Benkard12a57352021-12-28 18:02:04 +010081
82 try {
83 $body = $this->subparse($test, $dropNeedle);
84
85 if (null !== $this->parent && null === $body = $this->filterBodyNodes($body)) {
86 $body = new Node();
87 }
88 } catch (SyntaxError $e) {
89 if (!$e->getSourceContext()) {
90 $e->setSourceContext($this->stream->getSourceContext());
91 }
92
93 if (!$e->getTemplateLine()) {
94 $e->setTemplateLine($this->stream->getCurrent()->getLine());
95 }
96
97 throw $e;
98 }
99
100 $node = new ModuleNode(new BodyNode([$body]), $this->parent, new Node($this->blocks), new Node($this->macros), new Node($this->traits), $this->embeddedTemplates, $stream->getSourceContext());
101
102 $traverser = new NodeTraverser($this->env, $this->visitors);
103
104 $node = $traverser->traverse($node);
105
106 // restore previous stack so previous parse() call can resume working
107 foreach (array_pop($this->stack) as $key => $val) {
108 $this->$key = $val;
109 }
110
111 return $node;
112 }
113
114 public function subparse($test, bool $dropNeedle = false): Node
115 {
116 $lineno = $this->getCurrentToken()->getLine();
117 $rv = [];
118 while (!$this->stream->isEOF()) {
119 switch ($this->getCurrentToken()->getType()) {
120 case /* Token::TEXT_TYPE */ 0:
121 $token = $this->stream->next();
122 $rv[] = new TextNode($token->getValue(), $token->getLine());
123 break;
124
125 case /* Token::VAR_START_TYPE */ 2:
126 $token = $this->stream->next();
127 $expr = $this->expressionParser->parseExpression();
128 $this->stream->expect(/* Token::VAR_END_TYPE */ 4);
129 $rv[] = new PrintNode($expr, $token->getLine());
130 break;
131
132 case /* Token::BLOCK_START_TYPE */ 1:
133 $this->stream->next();
134 $token = $this->getCurrentToken();
135
136 if (/* Token::NAME_TYPE */ 5 !== $token->getType()) {
137 throw new SyntaxError('A block must start with a tag name.', $token->getLine(), $this->stream->getSourceContext());
138 }
139
140 if (null !== $test && $test($token)) {
141 if ($dropNeedle) {
142 $this->stream->next();
143 }
144
145 if (1 === \count($rv)) {
146 return $rv[0];
147 }
148
149 return new Node($rv, [], $lineno);
150 }
151
152 if (!$subparser = $this->env->getTokenParser($token->getValue())) {
153 if (null !== $test) {
154 $e = new SyntaxError(sprintf('Unexpected "%s" tag', $token->getValue()), $token->getLine(), $this->stream->getSourceContext());
155
156 if (\is_array($test) && isset($test[0]) && $test[0] instanceof TokenParserInterface) {
157 $e->appendMessage(sprintf(' (expecting closing tag for the "%s" tag defined near line %s).', $test[0]->getTag(), $lineno));
158 }
159 } else {
160 $e = new SyntaxError(sprintf('Unknown "%s" tag.', $token->getValue()), $token->getLine(), $this->stream->getSourceContext());
161 $e->addSuggestions($token->getValue(), array_keys($this->env->getTokenParsers()));
162 }
163
164 throw $e;
165 }
166
167 $this->stream->next();
168
169 $subparser->setParser($this);
170 $node = $subparser->parse($token);
171 if (null !== $node) {
172 $rv[] = $node;
173 }
174 break;
175
176 default:
177 throw new SyntaxError('Lexer or parser ended up in unsupported state.', $this->getCurrentToken()->getLine(), $this->stream->getSourceContext());
178 }
179 }
180
181 if (1 === \count($rv)) {
182 return $rv[0];
183 }
184
185 return new Node($rv, [], $lineno);
186 }
187
188 public function getBlockStack(): array
189 {
190 return $this->blockStack;
191 }
192
193 public function peekBlockStack()
194 {
195 return $this->blockStack[\count($this->blockStack) - 1] ?? null;
196 }
197
198 public function popBlockStack(): void
199 {
200 array_pop($this->blockStack);
201 }
202
203 public function pushBlockStack($name): void
204 {
205 $this->blockStack[] = $name;
206 }
207
208 public function hasBlock(string $name): bool
209 {
210 return isset($this->blocks[$name]);
211 }
212
213 public function getBlock(string $name): Node
214 {
215 return $this->blocks[$name];
216 }
217
218 public function setBlock(string $name, BlockNode $value): void
219 {
220 $this->blocks[$name] = new BodyNode([$value], [], $value->getTemplateLine());
221 }
222
223 public function hasMacro(string $name): bool
224 {
225 return isset($this->macros[$name]);
226 }
227
228 public function setMacro(string $name, MacroNode $node): void
229 {
230 $this->macros[$name] = $node;
231 }
232
233 public function addTrait($trait): void
234 {
235 $this->traits[] = $trait;
236 }
237
238 public function hasTraits(): bool
239 {
240 return \count($this->traits) > 0;
241 }
242
243 public function embedTemplate(ModuleNode $template)
244 {
245 $template->setIndex(mt_rand());
246
247 $this->embeddedTemplates[] = $template;
248 }
249
250 public function addImportedSymbol(string $type, string $alias, string $name = null, AbstractExpression $node = null): void
251 {
252 $this->importedSymbols[0][$type][$alias] = ['name' => $name, 'node' => $node];
253 }
254
255 public function getImportedSymbol(string $type, string $alias)
256 {
257 // if the symbol does not exist in the current scope (0), try in the main/global scope (last index)
258 return $this->importedSymbols[0][$type][$alias] ?? ($this->importedSymbols[\count($this->importedSymbols) - 1][$type][$alias] ?? null);
259 }
260
261 public function isMainScope(): bool
262 {
263 return 1 === \count($this->importedSymbols);
264 }
265
266 public function pushLocalScope(): void
267 {
268 array_unshift($this->importedSymbols, []);
269 }
270
271 public function popLocalScope(): void
272 {
273 array_shift($this->importedSymbols);
274 }
275
276 public function getExpressionParser(): ExpressionParser
277 {
278 return $this->expressionParser;
279 }
280
281 public function getParent(): ?Node
282 {
283 return $this->parent;
284 }
285
286 public function setParent(?Node $parent): void
287 {
288 $this->parent = $parent;
289 }
290
291 public function getStream(): TokenStream
292 {
293 return $this->stream;
294 }
295
296 public function getCurrentToken(): Token
297 {
298 return $this->stream->getCurrent();
299 }
300
301 private function filterBodyNodes(Node $node, bool $nested = false): ?Node
302 {
303 // check that the body does not contain non-empty output nodes
304 if (
305 ($node instanceof TextNode && !ctype_space($node->getAttribute('data')))
306 ||
307 (!$node instanceof TextNode && !$node instanceof BlockReferenceNode && $node instanceof NodeOutputInterface)
308 ) {
309 if (false !== strpos((string) $node, \chr(0xEF).\chr(0xBB).\chr(0xBF))) {
310 $t = substr($node->getAttribute('data'), 3);
311 if ('' === $t || ctype_space($t)) {
312 // bypass empty nodes starting with a BOM
313 return null;
314 }
315 }
316
317 throw new SyntaxError('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());
318 }
319
320 // bypass nodes that "capture" the output
321 if ($node instanceof NodeCaptureInterface) {
322 // a "block" tag in such a node will serve as a block definition AND be displayed in place as well
323 return $node;
324 }
325
326 // "block" tags that are not captured (see above) are only used for defining
327 // the content of the block. In such a case, nesting it does not work as
328 // expected as the definition is not part of the default template code flow.
329 if ($nested && $node instanceof BlockReferenceNode) {
330 throw new SyntaxError('A block definition cannot be nested under non-capturing nodes.', $node->getTemplateLine(), $this->stream->getSourceContext());
331 }
332
333 if ($node instanceof NodeOutputInterface) {
334 return null;
335 }
336
337 // here, $nested means "being at the root level of a child template"
338 // we need to discard the wrapping "Node" for the "body" node
339 $nested = $nested || Node::class !== \get_class($node);
340 foreach ($node as $k => $n) {
341 if (null !== $n && null === $this->filterBodyNodes($n, $nested)) {
342 $node->removeNode($k);
343 }
344 }
345
346 return $node;
347 }
348}