mrmitzh
mrmitzh

Reputation: 35

ANTLR: How to change the generated AST based on the rule we parse?

Is it possible for ANTLR to change the AST depends on the condition we have during parsing?

For example, when parsing a string like: foo().dropLastBar(true).bar(), we hope to drop the last occurrence of the bar if we have know that there is dropLastBar(true) exists.

Now I have used "members" in ANTLR to record whether there exists dropLastBar with true value. But I don't know how to modify the rule of ANTLR, so that the generated AST will be different based on the string we have. The string can be foo().dropLastBar(true).bar().bar().bar(), then is it possible for us to get the AST generated by foo().dropLastBar(true).bar().bar() without parsing twice?

Upvotes: 2

Views: 323

Answers (1)

Mike Lischke
Mike Lischke

Reputation: 53307

I think you complicate things unnecessarily here. The parser is a syntax tool. ANTLR4 based parsers generate a parse tree (not an AST btw.), which represents the input it got, according to the specified grammar.

What you are after is semantic handling, which is not the task of a parser and it isn't made for that anyway. Instead do a semantic step after the parse run, where you process the parse tree to extract the informations you need. Trying to force such handling into the grammar/parser is not going to work well (as it will slow down the parser and will make it way more complicated).

Upvotes: 5

Related Questions