1<?php 2 3declare(strict_types=1); 4 5namespace Antlr\Antlr4\Runtime; 6 7use Antlr\Antlr4\Runtime\Tree\ErrorNode; 8use Antlr\Antlr4\Runtime\Tree\ParseTreeListener; 9use Antlr\Antlr4\Runtime\Tree\TerminalNode; 10 11final class ParserTraceListener implements ParseTreeListener 12{ 13 /** @var Parser */ 14 public $parser; 15 16 public function __construct(Parser $parser) 17 { 18 $this->parser = $parser; 19 } 20 21 public function enterEveryRule(ParserRuleContext $context) : void 22 { 23 $stream = $this->parser->getTokenStream(); 24 $token = $stream !== null ? $stream->LT(1) : null; 25 26 echo \sprintf( 27 'enter %s, LT(1)=%s', 28 $this->parser->getRuleNames()[$context->getRuleIndex()], 29 $token === null? '' : $token->getText() ?? '' 30 ); 31 } 32 33 public function visitTerminal(TerminalNode $node) : void 34 { 35 echo \sprintf( 36 'consume %s rule %s', 37 $node->getSymbol(), 38 $this->parser->getCurrentRuleName() 39 ); 40 } 41 42 public function exitEveryRule(ParserRuleContext $context) : void 43 { 44 $stream = $this->parser->getTokenStream(); 45 $token = $stream !== null ? $stream->LT(1) : null; 46 47 echo \sprintf( 48 'exit %s, LT(1)=%s', 49 $this->parser->getRuleNames()[$context->getRuleIndex()], 50 $token === null? '' : $token->getText() ?? '' 51 ); 52 } 53 54 public function visitErrorNode(ErrorNode $node) : void 55 { 56 } 57} 58