ANTLR : rules with arguments?

antlr, antlr3, java

Solution

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

Problem

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

Original source