简体   繁体   中英

Get values from star/plus rules in ANTLR

I'm writing an ANTLR grammar (compiled into java) and I have the following code:

program returns [Program value]
    : PROGRAM d=decl* s=stmt+ END {$value = new Program($d.value, $s.value);}
    ;

decl returns [Declaration value]
    : ...

stmt returns [Statement value]
    : ...

The rule decl returns a Declaration object and stmt returns a Statement object. In this case however I have a "*" and a "+" after the rules meaning they could be returning many objects. In the generated parser, a single decl becomes a Declaration object but a decl* becomes: ((d != null) ? ((MyLang.decl_return) d).value : null)

How do I get a list of Declaration objects out of this?

I ended up working around this by adding a rule to accommodate the star and the plus (only star shown below but the concept is the same for the plus):

program returns [Program value]
    : PROGRAM d=zeroOrMoreDecl s=oneOrMoreStmt END {$value = new Program($d.value, $s.value);}
    ;

zeroOrMoreDecl returns [ArrayList<Declaration> value]
    : {$value = new ArrayList<Declaration>();} (d=decl {$value.add($d.value);})*
    ;

decl returns [Declaration value]
    : ...

I'm not a fan of cluttering up the code but it was the only solution I found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM