Search code examples
antlrantlr3antlr4abstract-syntax-treeantlrworks

AST Rule rewriting


I have the following rule and rule rewriting for AST in antlr:


param_name
    :   name subscript? initial_value? (',' name subscript? initial_value?)*  ';' -> ^(name subscript? initial_value?)*
    ;   

The problem is that i found out that i am not allowed to put a * in the rule rewriting at the place where i have put it. Can anyone suggest a different solution to this? I hope that from my rewritten rule, you can understand what I am trying to achieve.


Solution

  • Try something like this:

    grammar T;
    
    ...
    
    tokens {
      PARAMS;
    }
    
    ...
    
    param_names
     : param_name (',' param_name)*  ';' -> ^(PARAMS param_name+)
     ;
    
    param_name
     : name subscript? initial_value? -> ^(name subscript? initial_value?)
     ;
    
    ...
    

    If name is an AST as well (opposed to being a single token), you might want to try something like this:

    grammar T;
    
    ...
    
    tokens {
      PARAMS;
      PARAM;
    }
    
    ...
    
    param_names
     : param_name (',' param_name)*  ';' -> ^(PARAMS param_name+)
     ;
    
    param_name
     : name subscript? initial_value? -> ^(PARAM name subscript? initial_value?)
     ;
    
    ...