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

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

问题描述

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

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

类似于 Antlr-Pseudo-Code 中的这个日志函数,它应该显示一些规则的开始和结束位置 与每个 log() 交出 $start- 和 $end-tokens- 电话:

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 方法返回一个无效.从 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,每个解析器规则都会创建(并返回)一个 的实例ParserRuleReturnScope 调用了 retval:所以你可以将它用于你的目的:

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天全站免登陆