ANTLR : rules with arguments?

烈酒焚心 提交于 2019-12-10 11:16:24

问题


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 .

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();
     }
;

回答1:


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

An example of rule parameters:

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')+
 ;

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


来源:https://stackoverflow.com/questions/21747097/antlr-rules-with-arguments

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