-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathParser.php
More file actions
633 lines (523 loc) · 22.2 KB
/
Parser.php
File metadata and controls
633 lines (523 loc) · 22.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
use Twig\Error\SyntaxError;
use Twig\ExpressionParser\ExpressionParserInterface;
use Twig\ExpressionParser\ExpressionParsers;
use Twig\ExpressionParser\ExpressionParserType;
use Twig\ExpressionParser\InfixExpressionParserInterface;
use Twig\ExpressionParser\Prefix\LiteralExpressionParser;
use Twig\ExpressionParser\PrefixExpressionParserInterface;
use Twig\Node\BlockNode;
use Twig\Node\BlockReferenceNode;
use Twig\Node\BodyNode;
use Twig\Node\EmptyNode;
use Twig\Node\Expression\AbstractExpression;
use Twig\Node\Expression\Variable\AssignTemplateVariable;
use Twig\Node\Expression\Variable\TemplateVariable;
use Twig\Node\MacroNode;
use Twig\Node\ModuleNode;
use Twig\Node\Node;
use Twig\Node\NodeCaptureInterface;
use Twig\Node\NodeOutputInterface;
use Twig\Node\Nodes;
use Twig\Node\PrintNode;
use Twig\Node\TextNode;
use Twig\TokenParser\TokenParserInterface;
use Twig\Util\ReflectionCallable;
/**
* @author Fabien Potencier <[email protected]>
*/
class Parser
{
private $stack = [];
private ?\WeakMap $expressionRefs = null;
private $stream;
private $parent;
private $visitors;
private $expressionParser;
private $blocks;
private $blockStack;
private $macros;
private $importedSymbols;
private $traits;
private $embeddedTemplates = [];
private $varNameSalt = 0;
private $ignoreUnknownTwigCallables = false;
private ExpressionParsers $parsers;
public function __construct(
private Environment $env,
) {
$this->parsers = $env->getExpressionParsers();
}
public function getEnvironment(): Environment
{
return $this->env;
}
public function getVarName(): string
{
trigger_deprecation('twig/twig', '3.15', 'The "%s()" method is deprecated.', __METHOD__);
return \sprintf('__internal_parse_%d', $this->varNameSalt++);
}
/**
* @throws SyntaxError
*/
public function parse(TokenStream $stream, $test = null, bool $dropNeedle = false): ModuleNode
{
$vars = get_object_vars($this);
unset($vars['stack'], $vars['env'], $vars['handlers'], $vars['visitors'], $vars['expressionParser'], $vars['reservedMacroNames'], $vars['varNameSalt']);
$this->stack[] = $vars;
// node visitors
if (null === $this->visitors) {
$this->visitors = $this->env->getNodeVisitors();
}
$this->stream = $stream;
$this->parent = null;
$this->blocks = [];
$this->macros = [];
$this->traits = [];
$this->blockStack = [];
$this->importedSymbols = [[]];
$this->embeddedTemplates = [];
$this->expressionRefs = new \WeakMap();
try {
$body = $this->subparse($test, $dropNeedle);
if (null !== $this->parent && null === $body = $this->filterBodyNodes($body)) {
$body = new EmptyNode();
}
} catch (SyntaxError $e) {
if (!$e->getSourceContext()) {
$e->setSourceContext($this->stream->getSourceContext());
}
if (!$e->getTemplateLine()) {
$e->setTemplateLine($this->getCurrentToken()->getLine());
}
throw $e;
} finally {
$this->expressionRefs = null;
}
$node = new ModuleNode(
new BodyNode([$body]),
$this->parent,
$this->blocks ? new Nodes($this->blocks) : new EmptyNode(),
$this->macros ? new Nodes($this->macros) : new EmptyNode(),
$this->traits ? new Nodes($this->traits) : new EmptyNode(),
$this->embeddedTemplates ? new Nodes($this->embeddedTemplates) : new EmptyNode(),
$stream->getSourceContext(),
);
$traverser = new NodeTraverser($this->env, $this->visitors);
/**
* @var ModuleNode $node
*/
$node = $traverser->traverse($node);
// restore previous stack so previous parse() call can resume working
foreach (array_pop($this->stack) as $key => $val) {
$this->$key = $val;
}
return $node;
}
public function shouldIgnoreUnknownTwigCallables(): bool
{
return $this->ignoreUnknownTwigCallables;
}
public function subparseIgnoreUnknownTwigCallables($test, bool $dropNeedle = false): void
{
$previous = $this->ignoreUnknownTwigCallables;
$this->ignoreUnknownTwigCallables = true;
try {
$this->subparse($test, $dropNeedle);
} finally {
$this->ignoreUnknownTwigCallables = $previous;
}
}
/**
* @throws SyntaxError
*/
public function subparse($test, bool $dropNeedle = false): Node
{
$lineno = $this->getCurrentToken()->getLine();
$rv = [];
while (!$this->stream->isEOF()) {
switch (true) {
case $this->stream->getCurrent()->test(Token::TEXT_TYPE):
$token = $this->stream->next();
$rv[] = new TextNode($token->getValue(), $token->getLine());
break;
case $this->stream->getCurrent()->test(Token::VAR_START_TYPE):
$token = $this->stream->next();
$expr = $this->parseExpression();
$this->stream->expect(Token::VAR_END_TYPE);
$rv[] = new PrintNode($expr, $token->getLine());
break;
case $this->stream->getCurrent()->test(Token::BLOCK_START_TYPE):
$this->stream->next();
$token = $this->getCurrentToken();
if (!$token->test(Token::NAME_TYPE)) {
throw new SyntaxError('A block must start with a tag name.', $token->getLine(), $this->stream->getSourceContext());
}
if (null !== $test && $test($token)) {
if ($dropNeedle) {
$this->stream->next();
}
if (1 === \count($rv)) {
return $rv[0];
}
return new Nodes($rv, $lineno);
}
if (!$subparser = $this->env->getTokenParser($token->getValue())) {
if (null !== $test) {
$e = new SyntaxError(\sprintf('Unexpected "%s" tag', $token->getValue()), $token->getLine(), $this->stream->getSourceContext());
$callable = (new ReflectionCallable(new TwigTest('decision', $test)))->getCallable();
if (\is_array($callable) && $callable[0] instanceof TokenParserInterface) {
$e->appendMessage(\sprintf(' (expecting closing tag for the "%s" tag defined near line %s).', $callable[0]->getTag(), $lineno));
}
} else {
$e = new SyntaxError(\sprintf('Unknown "%s" tag.', $token->getValue()), $token->getLine(), $this->stream->getSourceContext());
$e->addSuggestions($token->getValue(), array_keys($this->env->getTokenParsers()));
}
throw $e;
}
$this->stream->next();
$subparser->setParser($this);
$node = $subparser->parse($token);
if (!$node) {
trigger_deprecation('twig/twig', '3.12', 'Returning "null" from "%s" is deprecated and forbidden by "TokenParserInterface".', $subparser::class);
} else {
$node->setNodeTag($subparser->getTag());
$rv[] = $node;
}
break;
default:
throw new SyntaxError('The lexer or the parser ended up in an unsupported state.', $this->getCurrentToken()->getLine(), $this->stream->getSourceContext());
}
}
if (1 === \count($rv)) {
return $rv[0];
}
return new Nodes($rv, $lineno);
}
public function getBlockStack(): array
{
trigger_deprecation('twig/twig', '3.12', 'Method "%s()" is deprecated.', __METHOD__);
return $this->blockStack;
}
/**
* @return string|null
*/
public function peekBlockStack()
{
return $this->blockStack[\count($this->blockStack) - 1] ?? null;
}
public function popBlockStack(): void
{
array_pop($this->blockStack);
}
public function pushBlockStack($name): void
{
$this->blockStack[] = $name;
}
public function hasBlock(string $name): bool
{
trigger_deprecation('twig/twig', '3.12', 'Method "%s()" is deprecated.', __METHOD__);
return isset($this->blocks[$name]);
}
public function getBlock(string $name): Node
{
trigger_deprecation('twig/twig', '3.12', 'Method "%s()" is deprecated.', __METHOD__);
return $this->blocks[$name];
}
public function setBlock(string $name, BlockNode $value): void
{
if (isset($this->blocks[$name])) {
throw new SyntaxError(\sprintf("The block '%s' has already been defined line %d.", $name, $this->blocks[$name]->getTemplateLine()), $this->getCurrentToken()->getLine(), $this->blocks[$name]->getSourceContext());
}
$this->blocks[$name] = new BodyNode([$value], [], $value->getTemplateLine());
}
public function hasMacro(string $name): bool
{
trigger_deprecation('twig/twig', '3.12', 'Method "%s()" is deprecated.', __METHOD__);
return isset($this->macros[$name]);
}
public function setMacro(string $name, MacroNode $node): void
{
$this->macros[$name] = $node;
}
public function addTrait($trait): void
{
$this->traits[] = $trait;
}
public function hasTraits(): bool
{
trigger_deprecation('twig/twig', '3.12', 'Method "%s()" is deprecated.', __METHOD__);
return \count($this->traits) > 0;
}
/**
* @return void
*/
public function embedTemplate(ModuleNode $template)
{
$template->setIndex(mt_rand());
$this->embeddedTemplates[] = $template;
}
public function addImportedSymbol(string $type, string $alias, ?string $name = null, AbstractExpression|AssignTemplateVariable|null $internalRef = null): void
{
if ($internalRef && !$internalRef instanceof AssignTemplateVariable) {
trigger_deprecation('twig/twig', '3.15', 'Not passing a "%s" instance as an internal reference is deprecated ("%s" given).', __METHOD__, AssignTemplateVariable::class, $internalRef::class);
$internalRef = new AssignTemplateVariable(new TemplateVariable($internalRef->getAttribute('name'), $internalRef->getTemplateLine()), $internalRef->getAttribute('global'));
}
$this->importedSymbols[0][$type][$alias] = ['name' => $name, 'node' => $internalRef];
}
/**
* @return array{name: string, node: AssignTemplateVariable|null}|null
*/
public function getImportedSymbol(string $type, string $alias)
{
// if the symbol does not exist in the current scope (0), try in the main/global scope (last index)
return $this->importedSymbols[0][$type][$alias] ?? ($this->importedSymbols[\count($this->importedSymbols) - 1][$type][$alias] ?? null);
}
public function isMainScope(): bool
{
return 1 === \count($this->importedSymbols);
}
public function pushLocalScope(): void
{
array_unshift($this->importedSymbols, []);
}
public function popLocalScope(): void
{
array_shift($this->importedSymbols);
}
/**
* @deprecated since Twig 3.21
*/
public function getExpressionParser(): ExpressionParser
{
trigger_deprecation('twig/twig', '3.21', 'Method "%s()" is deprecated, use "parseExpression()" instead.', __METHOD__);
if (null === $this->expressionParser) {
$this->expressionParser = new ExpressionParser($this, $this->env);
}
return $this->expressionParser;
}
public function parseExpression(int $precedence = 0): AbstractExpression
{
$token = $this->getCurrentToken();
if ($token->test(Token::OPERATOR_TYPE) && $ep = $this->parsers->getByName(PrefixExpressionParserInterface::class, $token->getValue())) {
$this->getStream()->next();
$expr = $ep->parse($this, $token);
$this->checkPrecedenceDeprecations($ep, $expr);
} else {
$expr = $this->parsers->getByClass(LiteralExpressionParser::class)->parse($this, $token);
}
$token = $this->getCurrentToken();
while ($token->test(Token::OPERATOR_TYPE) && ($ep = $this->parsers->getByName(InfixExpressionParserInterface::class, $token->getValue())) && $ep->getPrecedence() >= $precedence) {
$this->getStream()->next();
$expr = $ep->parse($this, $expr, $token);
$this->checkPrecedenceDeprecations($ep, $expr);
$token = $this->getCurrentToken();
}
return $expr;
}
public function getParent(): ?Node
{
trigger_deprecation('twig/twig', '3.12', 'Method "%s()" is deprecated.', __METHOD__);
return $this->parent;
}
/**
* @return bool
*/
public function hasInheritance()
{
return $this->parent || 0 < \count($this->traits);
}
public function setParent(?Node $parent): void
{
if (null === $parent) {
trigger_deprecation('twig/twig', '3.12', 'Passing "null" to "%s()" is deprecated.', __METHOD__);
}
if (null !== $parent && !$parent instanceof AbstractExpression) {
trigger_deprecation('twig/twig', '3.24', 'Passing a "%s" instance to "%s()" is deprecated, pass an "AbstractExpression" instance instead.', $parent::class, __METHOD__);
}
if (null !== $this->parent) {
throw new SyntaxError('Multiple extends tags are forbidden.', $parent->getTemplateLine(), $parent->getSourceContext());
}
$this->parent = $parent;
}
public function getStream(): TokenStream
{
return $this->stream;
}
public function getCurrentToken(): Token
{
return $this->stream->getCurrent();
}
public function getFunction(string $name, int $line): TwigFunction
{
try {
$function = $this->env->getFunction($name);
} catch (SyntaxError $e) {
if (!$this->shouldIgnoreUnknownTwigCallables()) {
throw $e;
}
$function = null;
}
if (!$function) {
if ($this->shouldIgnoreUnknownTwigCallables()) {
return new TwigFunction($name, static fn () => '');
}
$e = new SyntaxError(\sprintf('Unknown "%s" function.', $name), $line, $this->stream->getSourceContext());
$e->addSuggestions($name, array_keys($this->env->getFunctions()));
throw $e;
}
if ($function->isDeprecated()) {
$src = $this->stream->getSourceContext();
$function->triggerDeprecation($src->getPath() ?: $src->getName(), $line);
}
return $function;
}
public function getFilter(string $name, int $line): TwigFilter
{
try {
$filter = $this->env->getFilter($name);
} catch (SyntaxError $e) {
if (!$this->shouldIgnoreUnknownTwigCallables()) {
throw $e;
}
$filter = null;
}
if (!$filter) {
if ($this->shouldIgnoreUnknownTwigCallables()) {
return new TwigFilter($name, static fn () => '');
}
$e = new SyntaxError(\sprintf('Unknown "%s" filter.', $name), $line, $this->stream->getSourceContext());
$e->addSuggestions($name, array_keys($this->env->getFilters()));
throw $e;
}
if ($filter->isDeprecated()) {
$src = $this->stream->getSourceContext();
$filter->triggerDeprecation($src->getPath() ?: $src->getName(), $line);
}
return $filter;
}
public function getTest(int $line): TwigTest
{
$name = $this->stream->expect(Token::NAME_TYPE)->getValue();
if ($this->stream->test(Token::NAME_TYPE)) {
// try 2-words tests
$name = $name.' '.$this->getCurrentToken()->getValue();
try {
$test = $this->env->getTest($name);
} catch (SyntaxError $e) {
if (!$this->shouldIgnoreUnknownTwigCallables()) {
throw $e;
}
$test = null;
}
$this->stream->next();
} else {
try {
$test = $this->env->getTest($name);
} catch (SyntaxError $e) {
if (!$this->shouldIgnoreUnknownTwigCallables()) {
throw $e;
}
$test = null;
}
}
if (!$test) {
if ($this->shouldIgnoreUnknownTwigCallables()) {
return new TwigTest($name, static fn () => '');
}
$e = new SyntaxError(\sprintf('Unknown "%s" test.', $name), $line, $this->stream->getSourceContext());
$e->addSuggestions($name, array_keys($this->env->getTests()));
throw $e;
}
if ($test->isDeprecated()) {
$src = $this->stream->getSourceContext();
$test->triggerDeprecation($src->getPath() ?: $src->getName(), $this->stream->getCurrent()->getLine());
}
return $test;
}
private function filterBodyNodes(Node $node, bool $nested = false): ?Node
{
// check that the body does not contain non-empty output nodes
if (
($node instanceof TextNode && !ctype_space($node->getAttribute('data')))
|| (!$node instanceof TextNode && !$node instanceof BlockReferenceNode && $node instanceof NodeOutputInterface)
) {
if (str_contains((string) $node, \chr(0xEF).\chr(0xBB).\chr(0xBF))) {
$t = substr($node->getAttribute('data'), 3);
if ('' === $t || ctype_space($t)) {
// bypass empty nodes starting with a BOM
return null;
}
}
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());
}
// bypass nodes that "capture" the output
if ($node instanceof NodeCaptureInterface) {
// a "block" tag in such a node will serve as a block definition AND be displayed in place as well
return $node;
}
// "block" tags that are not captured (see above) are only used for defining
// the content of the block. In such a case, nesting it does not work as
// expected as the definition is not part of the default template code flow.
if ($nested && $node instanceof BlockReferenceNode) {
throw new SyntaxError('A block definition cannot be nested under non-capturing nodes.', $node->getTemplateLine(), $this->stream->getSourceContext());
}
if ($node instanceof NodeOutputInterface) {
return null;
}
// here, $nested means "being at the root level of a child template"
// we need to discard the wrapping "Node" for the "body" node
// Node::class !== \get_class($node) should be removed in Twig 4.0
$nested = $nested || (Node::class !== $node::class && !$node instanceof Nodes);
foreach ($node as $k => $n) {
if (null !== $n && null === $this->filterBodyNodes($n, $nested)) {
$node->removeNode($k);
}
}
return $node;
}
private function checkPrecedenceDeprecations(ExpressionParserInterface $expressionParser, AbstractExpression $expr)
{
$this->expressionRefs[$expr] = $expressionParser;
$precedenceChanges = $this->parsers->getPrecedenceChanges();
// Check that the all nodes that are between the 2 precedences have explicit parentheses
if (!isset($precedenceChanges[$expressionParser])) {
return;
}
if ($expr->hasExplicitParentheses()) {
return;
}
if ($expressionParser instanceof PrefixExpressionParserInterface) {
/** @var AbstractExpression $node */
$node = $expr->getNode('node');
foreach ($precedenceChanges as $ep => $changes) {
if (!\in_array($expressionParser, $changes, true)) {
continue;
}
if (isset($this->expressionRefs[$node]) && $ep === $this->expressionRefs[$node]) {
$change = $expressionParser->getPrecedenceChange();
trigger_deprecation($change->getPackage(), $change->getVersion(), \sprintf('As the "%s" %s operator will change its precedence in the next major version, add explicit parentheses to avoid behavior change in "%s" at line %d.', $expressionParser->getName(), ExpressionParserType::getType($expressionParser)->value, $this->getStream()->getSourceContext()->getName(), $node->getTemplateLine()));
}
}
}
foreach ($precedenceChanges[$expressionParser] as $ep) {
foreach ($expr as $node) {
/** @var AbstractExpression $node */
if (isset($this->expressionRefs[$node]) && $ep === $this->expressionRefs[$node] && !$node->hasExplicitParentheses()) {
$change = $ep->getPrecedenceChange();
trigger_deprecation($change->getPackage(), $change->getVersion(), \sprintf('As the "%s" %s operator will change its precedence in the next major version, add explicit parentheses to avoid behavior change in "%s" at line %d.', $ep->getName(), ExpressionParserType::getType($ep)->value, $this->getStream()->getSourceContext()->getName(), $node->getTemplateLine()));
}
}
}
}
}