How to sort products in ANTLR

Assume the following scenarios with two ANTLR grammars:

1)

expr     : antExp+;
antExpr  : '{' T '}' ;
T        : 'foo';

2)

expr     : antExpr; 
antExpr  : '{' T* '}' ;
T        : 'bar';

In both cases, I need to know how to iterate over antExp + and T *, because I need to create an ArrayList for each of them. Of course, my grammar is more complicated, but I think this example should explain what I need. Thank!

+5
source share
1 answer

ANTLR production rules can have one or more return types that you can reference within a loop (a (...)*or (...)+). So, let's say you want to print every text Tthat matches the rule antExp. This can be done as follows:

expr
 : (antExp {System.out.println($antExp.str);} )+
 ;

antExpr returns [String str]
 : '{' T '}' {$str = $T.text;}
 ;

T : 'foo';

The same principle holds, for example, in grammar number 2:

expr     : antExpr; 
antExpr  : '{' (T {System.out.println($T.text);} )* '}' ;
T        : 'bar';

EDIT

, . , :

grammar T;  

parse
 : ids {System.out.println($ids.firstId + "\n" + $ids.allIds);}
 ;

ids returns [String firstId, List<String> allIds]
@init{$allIds = new ArrayList<String>();}
@after{$firstId = $allIds.get(0);}
 : (ID {$allIds.add($ID.text);})+
 ;

ID    : ('a'..'z' | 'A'..'Z')+;
SPACE : ' ' {skip();};

"aaa bbb ccc" :

aaa
[aaa, bbb, ccc]
+6

All Articles