[antlr-interest] Tree Evaluation with Logical Operators (AND and OR)

Oliver Zeigermann oliver.zeigermann at gmail.com
Thu Jan 22 05:12:48 PST 2009


2009/1/22 shmuel siegel <antlr at shmuelhome.mine.nu>:
> Oliver Zeigermann wrote:
>>
>> OK, so you need a tree grammar that can parse complex boolean
>> expressions, right?
>>
>> expression
>>  : ^((AND|OR) expression expression)
>>  | ^(('<'|'>'|'='|'!=') expression expression)
>>  | ^(('+'|'-'|'*'|'/') expression expression)
>>  | ID
>>  | literal
>>  ;
>>
>> Would that work?
>>
>> -Oliver
>>
>>
>
> This grammar is not syntactically restrictive since it allows ^(AND 3 4).
> This will cause problems if you want to evaluate the tree since you won't
> know the type of the return value of expression. It is better to separate
> out arithmetic and logical expressions. Care must be taken to establish if
> ID is arithmetic or logical.
>
>

You can solve this by adding a synthetic type attribute to the
expression and check for compatibility with each operator.

Like

expression returns [Object value, String type]
 : ^((AND|OR) e1=expression e2=expression) {$e1.type.equals("boolean")
&& $e2.type.equals("boolean")}?
       { $type = "boolean"; }
 | ...
 ;

- Oliver


More information about the antlr-interest mailing list