How to handle return values ​​in ANTLR

What is the correct way to solve this problem in ANTLR:

I have a simple grammar rule, for example, for a list with an arbitrary number of elements.

list
: '[]' 
| '[' value (COMMA value)* ']'

If I wanted to assign a return value to a list, and does that value have an actual list of return values ​​from production, what is its correct way? The alternatives that I occupy are:

  • create your own stack in the global area to keep track of these lists.
  • Try checking the nodes of the tree below me and extract the information this way
  • Access to it in some smooth and cool way, which I hope to learn about, in which I can get easy access to such a list from the action associated with this rule.

I think the question is, how do cool kids do it?

(FYI I use the python API for ANTLR, but if you hit me with another language, I can handle this)

+5
source share
2 answers

In C #, it might look like this:

list returns [ List<string> ValueList ]
    @init
    {
        $ValueList = new List<string>();
    }
    : '[]'
    | '[' value {$ValueList.Add(value);} (COMMA value {$ValueList.Add(value);})* ']'
    ;
+5
source

I think an easier way might be

list returns [ List values ]
: '[]' 
| '[' vs+=value (COMMA vs+=value)* ']' {
        $values = $vs;
}
+1
source

All Articles