Antlr4 Visitor several rule contexts

故事扮演 提交于 2019-12-11 01:37:14

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/36445688/antlr4-visitor-several-rule-contexts

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!