ANTLR4 can only parse a class statement, not the whole file Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of ANTLR4 can only parse a class statement, not the whole file without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I created a simple code to parse PHP file:

namespace aaa;

class Xyz {


I wrote a parser using ANTL4 and this grammar:

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();



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:


class Xyz {


everything is fine.

How to fix that?


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:


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.

We are here to answer your question about ANTLR4 can only parse a class statement, not the whole file - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji