获取活动的Antlr规则 [英] Get active Antlr rule

查看:71
本文介绍了获取活动的Antlr规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从中调用操作方法的活动" ANTLR规则?

Is it possible to get the "active" ANTLR rule from which a action method was called?

类似于Antlr-Pseudo-Code中的log函数的东西,该函数应该显示某些规则的开始和结束位置而无需随每个log()移交$ start-和$ end-token呼叫:

Something like this log-function in Antlr-Pseudo-Code which should show the start and end position of some rules without hand over the $start- and $end-tokens with every log()-call:

@members{
  private void log() {
    System.out.println("Start: " + $activeRule.start.pos +
                       "End: " + $activeRule.stop.pos);
  }
}

expr: multExpr (('+'|'-') multExpr)* {log(); }
    ;

multExpr
    : atom('*' atom)* {log(); }
    ;

atom: INT
    | ID {log(); }
    | '(' expr ')'
    ;

推荐答案

否,无法获取解析器当前所在的规则的名称.请注意,解析器规则默认是简单的Java方法,返回一个void.在Java方法中,您毕竟无法在运行时(在此方法内部)找到它的名称.

No, there is no way to get the name of the rule the parser is currently in. Realize that parser rules are, by default, simply Java methods returning a void. From a Java method, you cannot find out the name of it at run-time after all (when inside of this method).

如果您在语法的options { ... }中设置output=AST,则每个解析器规则都会创建(并返回)名为retvalParserRuleReturnScope的实例:因此,您可以使用该实例为了您的目的:

If you set output=AST in the options { ... } of your grammar, every parser rule creates (and returns) an instance of a ParserRuleReturnScope called retval: so you could use that for your purposes:

// ...

options {
  output=AST;
}

// ...

@parser::members{
  private void log(ParserRuleReturnScope rule) {
    System.out.println("Rule: "    + rule.getClass().getName() +  
                       ", start: " + rule.start +
                       ", end: "   + rule.stop);
  }
}

expr: multExpr (('+'|'-') multExpr)*    {log(retval);}
    ;

multExpr
    : atom('*' atom)*                   {log(retval);}
    ;

atom: INT
    | ID                                {log(retval);}
    | '(' expr ')'
    ;
// ...

但这并不是一件很可靠的事情:在下一版ANTLR中,变量的名称可能会发生变化.

This is however not a very reliable thing to do: the name of the variable may very well change in the next version of ANTLR.

这篇关于获取活动的Antlr规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆