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

查看:21
本文介绍了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 ).

我也可以将参数传递给规则吗?我只是想通了,我想根据提供给它的参数来改变规则在 pertucular 状态下的行为.

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