How to deal with list return values in ANTLR

北城以北 提交于 2019-12-06 02:58:40

问题


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

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

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

If I wanted to assign a return value for list, and have that value be the actual list of returned values from the production, what is the proper way to do it? The alternatives I'm entertaining are:

  • create my own stack in the global scope to keep track of these lists
  • Try to inspect the tree nodes below me and extract information that way
  • Access it in some slick and cool way that I'm hoping to find out about in which I can get easy access to such a list from within the action associated with the rule.

I guess the question is: How do the cool kids do it?

(FYI I'm using the python API for ANTLR, but if you hit me with another language, I can handle that)


回答1:


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);})* ']'
    ;



回答2:


I guess a more straightforward way could be

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


来源:https://stackoverflow.com/questions/759028/how-to-deal-with-list-return-values-in-antlr

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