ANTLR:带有参数的规则? [英] ANTLR : rules with arguments?

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

问题描述

我是ANTLR的新手.我开始探索ANTLR教程.我看到了为垂直规则定义返回类型的示例(请参见下面的示例).

I am new to ANTLR. I started exploring ANTLR tutorials. I have seen example where return type have been defined for perticular rule(see below example ).

我也可以将参数传递给规则吗?我脑子里只有一点,我想根据提供给它的论据来改变规则状态下的规则行为.

Can I pass argument to rule as well ? I just have throught in my mind, i wanted to change the behavior of rule at a pertucular state based on argument provided to it .

如果它在ANTLR中可以通过,或者这样做是个好主意,请帮助我?

please help me if it passible in ANTLR or is it a good idea to do that ?

atom returns [int value]
 :
  INT 
     {
      $value = Integer.parseInt($INT.text);
     }
  | ID // variable reference
     {
      Integer v = (Integer) memory.get($ID.text);
      if (v != null)
        $value = v.intValue();
     }
;

推荐答案

是的,但是您不能将解析器规则中的参数传递给词法分析器规则:词法分析器独立于解析器构造令牌.

Yes, but you can't pass parameters from a parser rule into a lexer rule: the lexer constructs tokens independently from the parser.

规则参数示例:

parse
 : p1["param"]
 ;

p1 [String s]
 : ref=p2[$s, 42]
   {
     // Print some info about rule 'p2'.
     System.out.println("param=" + $s);
     System.out.println("p2.ss=" + $ref.ss);
     System.out.println("p2.ii=" + $ref.ii);
   }
 ;

// Rules can have more than 1 param, and can even return more than 1 value.
p2 [String s, int i] returns [String ss, int ii]
 : ID
   {
     $ss = $s + "_" + $ID.text;
     $ii = $i + $i;
   }
 ;

ID
 : ('a'..'z')+
 ;

如果您现在解析输入"mu",则会在控制台上显示以下内容:

If you'd now parse the input "mu", the following will be printed to your console:

param=param
p2.ss=param_mu
p2.ii=84

这篇关于ANTLR:带有参数的规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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