multiple return values in ANTLR

757 Views Asked by At

I use ANTLR4 with Java and I would like to store the values that a rule returns while parses the input. I use a grammar like this:

db : 'DB' '(' 'ID' '=' ID ',' query* ')'
{
System.out.println("creating db");
System.out.println("Number of queries -> "+$query.qs.size());
}
;

query returns [ArrayList<Query> qs] 
@init
{
    $qs = new ArrayList<Query>();
}
: 'QUERY' '(' 'ID' '=' ID ','  smth ')'
{
System.out.println("creating query with id "+$ID.text);
Query query = new Query();
query.setId($ID.text);
$qs.add(query);
}
;

but what happens is that the Number of queries printed ($query.qs size) is always one. This happens because each time a QUERY element is recognized at input it is added to the $qs ArrayList, but for each other QUERY a new ArrayList is instantiated and this query is added to this new ArrayList. When all the queries are recognized then the action for the db : rule is invoked, but the $query.qs ArrayList has only the last query. I solved this problem by maintaining global ArrayLists that store the queries. But, is there another way to do it with ANTLR while the rules are returning, and not having my own global ArrayLists?

Many thanks in advance, Dimos.

1

There are 1 best solutions below

0
On

Well, the problem is resolved. I just added the ArrayList to the db rule like this:

db [ArrayList queries] : 'DB' ....

and then at query rule:

$db::queries.add(query)

So, everything is fine!

Thanks for looking, anyway!