简体   繁体   中英

Handling ANTLR return values

I have a grammar rule like this:

a returns [string expr] : (b | c) {$expr = "Build expression from b OR c here";}

b returns [string expr] : 'B' {$expr = "From b";}

c returns [string expr] : 'C' {$expr = "From c";}

I would like to replace

$expr = "Build expression from b OR c here"; 

with an instruction that puts in the $expr variable whatever was returned from b OR c. I know there is a solution to this by performing this assignment like this:

a returns [string expr] : b {$expr = $b.expr;} | c {$expr = $c.expr;}

but was wondering whether there is a much simpler way like naming the whole group with a variable and using that instead:

a returns [string expr] : group = (b | c) {$expr = $group.expr;}

I've tried this and it doesn't work in ANTLR, even though the group variable is used to get the value returned by "b".

You cannot use the same label for multiple non-terminals unless they reference the same rule in the grammar. This means syntax like group=(A | B) only works for token references ( A and B are terminals). The following syntax can be used for this.

a returns [string expr]
    :   b {$expr = $b.expr;}
    |   c {$expr = $c.expr;}
    ;

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