-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathParseTreeWalker.php
76 lines (55 loc) · 1.86 KB
/
ParseTreeWalker.php
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
<?php
declare(strict_types=1);
namespace Antlr\Antlr4\Runtime\Tree;
use Antlr\Antlr4\Runtime\ParserRuleContext;
class ParseTreeWalker
{
public static function default(): self
{
static $instance;
return $instance ?? ($instance = new self());
}
public function walk(ParseTreeListener $listener, ParseTree $tree): void
{
if ($tree instanceof ErrorNode) {
$listener->visitErrorNode($tree);
return;
}
if ($tree instanceof TerminalNode) {
$listener->visitTerminal($tree);
return;
}
if (!$tree instanceof RuleNode) {
throw new \InvalidArgumentException('Unexpected tree type.');
}
$this->enterRule($listener, $tree);
$count = $tree->getChildCount();
for ($i = 0; $i < $count; $i++) {
$child = $tree->getChild($i);
if ($child !== null) {
$this->walk($listener, $child);
}
}
$this->exitRule($listener, $tree);
}
/**
* The discovery of a rule node, involves sending two events: the generic
* {@see ParseTreeListener::enterEveryRule()} and a
* {@see RuleContext}-specific event. First we trigger the generic and then
* the rule specific. We to them in reverse order upon finishing the node.
*/
protected function enterRule(ParseTreeListener $listener, RuleNode $ruleNode): void
{
/** @var ParserRuleContext $ctx */
$ctx = $ruleNode->getRuleContext();
$listener->enterEveryRule($ctx);
$ctx->enterRule($listener);
}
protected function exitRule(ParseTreeListener $listener, RuleNode $ruleNode): void
{
/** @var ParserRuleContext $ctx */
$ctx = $ruleNode->getRuleContext();
$ctx->exitRule($listener);
$listener->exitEveryRule($ctx);
}
}