Dims
Dims

Reputation: 51259

How to select Antlr4 starting rule at runtime?

Antlr4 creates methods inside extends Parser, which have names the same as rules. For example, if I have rule named "program" in my grammar, it will create method program(). I can call this method, to do parsing.

But what if I wish to select starting rule at runtime?

I looked at implementation and found the beginning

public final ProgramContext program() throws RecognitionException {
    ProgramContext _localctx = new ProgramContext(_ctx, getState());
    enterRule(_localctx, 0, RULE_program);

it implies, that I can't select rule by name or index, because I need two things simultaneously: ProgramContext class and RULE_program constant.

Is it possible in fact?

Can I define some default rule and call it automatically?

Upvotes: 1

Views: 765

Answers (3)

Ivan Kochurkin
Ivan Kochurkin

Reputation: 4501

As I understand you can choose any starting rule via reflection. I suggest the following code on Java as an example:

Method startMethod = parser.getClass().getMethod("customStartRule", new Class[] {});
ParserRuleContext ast = (ParserRuleContext)startMethod.invoke(parser, new Object[] {});

All start rules you can find in ruleNames array in generated parser.

Upvotes: 0

Mike Lischke
Mike Lischke

Reputation: 53582

No, this is not possible with the generated parser. However, look in the ParserInterpreter class (which allows to specify the start rule index). This class emulates the real parser but works differently than that and is probably not what you want, but maybe it gives you an idea.

Upvotes: 0

GRosenberg
GRosenberg

Reputation: 6001

All parser grammar rules are implemented by methods in the generated parser. If your grammar defines

program : .... ;
statemt : .... ;

the grammar will have methods

public final ProgramContext program() throws RecognitionException ....
public final StatemtContext statemt() throws RecognitionException ....

Either can be called as the start rule for evaluating a token stream.

See this answer suggesting a way to programmatically identify parser rules.

Upvotes: 1

Related Questions