antlr2 return multiple values

落爺英雄遲暮 提交于 2020-01-06 14:16:35

问题


How to make a rule return multiple values in antlr2.For example:

declSpecifiers returns [int mods]
        : ( storageClassSpecifier    
        | typeQualifier       
        | typeSpecifier)+
        ;

I have some other information besides 'mods' to return.What should I do?


回答1:


In ANTLR v3.x, you can include multiple return values by listing them in the brackets.

declSpecifiers returns [int mods, Object otherInfo]
        : ( storageClassSpecifier    
        | typeQualifier       
        | typeSpecifier)+
        ;

The generated code will return a generated class containing fields for all the return values, using the names you've provided.




回答2:


In ANTLR v2.x, you can only return a single value, unlike ANTLR v3.x where multiple return values are automatically wrapped by a container containing the multiple return values.

You'll have to return some sort of collection, or custom object:

declSpecifiers returns [Map map]
{map = new HashMap();}
  : ( storageClassSpecifier { /* populate your map here */ }
    | typeQualifier         { /* populate your map here */ }
    | typeSpecifier         { /* populate your map here */ }
    )+
  ;

I presume you know ANTLR v2 is rather old: if you can, migrate to v3 (I know that's not always an option... but still).



来源:https://stackoverflow.com/questions/8491388/antlr2-return-multiple-values

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