[antlr-interest] AST - Ordering of sibling nodes

Søren Boisen sboisen at mail.dk
Mon Feb 27 02:10:04 PST 2012


Hi there, I'm transforming a URL query language (OData) to SQL. In the
query language the query operators can be specified in arbitrary
sequence:

uri     :   resource ('?' query)? EOF
       ->  ^(URI resource query?) ;

query   :   queryOp ('&' queryOp)*
        ->  ^(QUERY queryOp+) ;

queryOp :	  expandQueryOp
        |	  orderByQueryOp
        |	  selectQueryOp
        |	  filterQueryOp ;

<--------snip--------->


However, in SQL I of course have to abide by a very specific ordering:

selectClause
fromClause
whereClause
orderByClause

The question is, what's the best/easiest/simplest way of reordering
the AST nodes, so they align with the SQL requirements?
Currently I'm generating the SQL via string templates like so:

uri     :   ^(URI clauses+=resource clauses+=queryOp*)
        ->  query(clauses={$clauses}) ;

resource:   ^(RESOURCE ID s=subResource*)
             -> fromClause(entity={entity($ID)}, joins={$s.st}) ;

queryOp	:   ^(SELECT items=selectItem+)        ->
selectClause(items={$items.st})
                |   ^(FILTER expr)                               ->
whereClause(condition={$expr.st})
                |   ^(ORDERBY items=orderByItem+)   ->
orderByClause(items={$items.st}) ;

<--------snip--------->

But this requires that the nodes are already sorted in the right order.

/Søren


More information about the antlr-interest mailing list