[antlr-interest] Translating expressions - advice?

Hans-Juergen Rennau hrennau at yahoo.de
Mon May 9 06:10:05 PDT 2011


Hello People,

being an ANTLR beginner, I would very much appreciate advice concerning good 
practise for a rather simple task. The task is the translation of a JPQL's (Java 
Persistence Query Language) "where clause" into a proprietary query language. 
The clause has the well-known expression structure: operands conncected by three 
operators: OR, AND and NOT, where precedence increases in that order. Example:
   a.x='1' AND (a.y='2' OR b.z='3') AND a.v like 'abc%'

An important point is that the translation result will have a similar structure, 
that is, it will also be operands connected by those operators. Example:
   x='1' AND (y='2' OR z='3') AND v='123*'

For this reason I am not sure if the "classical" approach for dealing with 
left-associative operators, as shown in the "Definitve ANTLR Reference" (3. A 
quick tour...) is the most appropriate one in this case. I mean rules like:
   conditional_term ('OR'^ conditional_term)*
   conditional_factor ('AND'^ conditional_factor)*

This creates deep trees, where each operator creates a new level. That is fine 
for processing the operations. But a straightforward translation of the tree 
into a similar sequence of operands and operators yields a result which is 
correct but can be ugly, due to superflous brackets, example:
   (a OR (b OR (c AND d)))

One possibility is to process the tree, removing superfluous brackets - perhaps 
by passing the "context operator" into the rule as a parameter, so that the rule 
can decide if to create brackets or not. This should not be too difficult, but 
my question is: is there a good practise for accomplishing the task? Would you 
recommend the approach just sketched, or a different tree representation to 
start with?

(A tree I do want because there are other parts to be translated, not only the 
where clause, and a tree seems to me the way to deal with (possibly yet growing) 
complexity.

Thank you very much for any suggestions.

-- Hans-Juergen



More information about the antlr-interest mailing list