Jordi
Jordi

Reputation: 23247

Antlr4 Visitor several rule contexts

I've a grammar like that:

search
 : K_SEARCH entity
 ( K_QUERY expr )?
 ( K_FILTER expr )?
;

As you can see I've two optional expr.

I've created my Visitor, and I'm able to get access to entity, K_QUERY and K_FILTER. SearchContext provides a List<ExprContext> in order to get a list of all expr. However, how can I know with expression is a K_QUERY expr or a K_FILTER expr?

public class LivingQueryVisitor extends LivingDSLBaseVisitor<Void> {

    @Override
    public Void visitSearch(SearchContext ctx) {
        this.query = search(this.getEntityPath(ctx));
        //???????????????????????
        List<ExprContext> exprs = ctx.expr();
        //???????????????????????
        return super.visitSearch(ctx);
    }
}

Any ideas?

Upvotes: 2

Views: 699

Answers (2)

GRosenberg
GRosenberg

Reputation: 6001

Just label the two expr terms.

search : K_SEARCH entity
       ( K_QUERY  q=expr )?
       ( K_FILTER f=expr )?
;

Antlr will generate two additional variables within the SearchContext class:

ExprContext q;
ExprContext f;

The values will be non-null iff the corresponding subterms matched.

Upvotes: 4

Divisadero
Divisadero

Reputation: 913

If you do now want to change the grammar that will enable you to do it in more elegant way, you can just use index. As there are two 'expr' in the rule, you expr[0] will be K_Query expression and expr[1] will be K_filter expresssion provided there are both tokens present. (K_Query and K_filter).

If not, expr[0] will be the expression of the existing token.

Upvotes: 1

Related Questions