The question is published on by Tutorial Guruji team.
I created a simple code to parse PHP file:
<?php namespace aaa; class Xyz { }
I wrote a parser using ANTL4 and this grammar: https://github.com/antlr/grammars-v4/tree/master/php:
PhpLexer lexer = new PhpLexer(new ANTLRInputStream((new BufferedReader(new FileReader("./code/test.php"))))); CommonTokenStream tokens = new CommonTokenStream(lexer); PhpParser parser = new PhpParser(tokens); PhpParserBaseListener listener = new PhpParserBaseListener(); parser.addParseListener(listener); parser.classDeclaration().enterRule(listener); parser.getSerializedATN();
It returns an error:
line 3:0 mismatched input ‘namespace’ expecting {‘abstract’, ‘class’, ‘final’, ‘interface’, ‘partial’, ‘private’, ‘trait’}
But when I remove “namespace aaa;” statement:
<?php class Xyz { }
everything is fine.
How to fix that?
Answer
Since you don’t show any of your grammar, it’s not possible to provide a specific answer. Also I really don’t know enough about the PHP runtime for Antlr to more than hazard a guess at what this does:
parser.classDeclaration().enterRule(listener);
But generally, Antlr4 creates an interface for every non-terminal rule, so I presume that parser.classDeclaration()
corresponds to the classDeclaration
rule, which presumably represents a class declaration, and not the entire program. Probably you should change classDeclaration
to whatever the top-level rule in your grammar is.