Handling ANTLR Return Values

I have a grammar rule:

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 variable $ expr everything that was returned from b OR c. I know there is a solution to this by completing this task as follows:

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

but wondered if there is a much simpler way how to name the entire group of a variable and use it instead:

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

I tried this and it does not work in ANTLR, although the batch variable is used to get the value returned by "b".

+4
source share
1 answer

You cannot use the same label for multiple non-terminals if they do not refer to the same rule in the grammar. This means that the syntax of type group=(A | B) works only for references to tokens ( A and B are terminals). You can use the following syntax for this.

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

Source: https://habr.com/ru/post/1483190/


All Articles