[antlr-interest] parsing boolean expressions: not not or abc

lord.of.board at gmx.de lord.of.board at gmx.de
Thu Jan 14 08:24:19 PST 2010


I received an email describing a working solution. See below:

-----------

Looks like it should work if you change term  to

  term    :       WORD | NOT | AND | OR ;

I tried it with a few examples and it seems to do ok.

(I added in ASTLabelType=CommonTree; in the options and printed
toStringTree() on the resulting tree and things look good.)

The problem is going to be showing syntax errors - because the
keywords are non-reserved it's more likely that something the user
didn't intend will acually parse.

If you can't stop people from using the keywords as terms, you should
at least discourage it.

Remember PL/I :
   IF IF = THEN THEN THEN = ELSE ELSE ELSE = IF;

Sigh... You can do it, but no one really did (if I recall my PL/I
syntax... been a while) and it was highly discouraged.

Good luck!
-- Scott

> Hello,
>
> I am trying to build a grammar which accepts boolean expressions for filtering. I found some interesting articles on the web, but now I got stuck.
> I try to parse something like this:
>
>  not not or abc
>
> The first "not" is the boolean operator and the second is a text.
>
> Or even worse
>
>  not not and not or and not and
>
> My grammar look like this:
>
> grammar TextFilterGrammar;
> options {
>        output=AST;
> }
> content :       orexpression
>        ;
> orexpression
>        :       andexpression (OR^ andexpression)*
>        ;
> andexpression
>        :       expression (AND^ expression)*
>        ;
> expression
>        :       (NOT^)? term
>        ;
> term    :       WORD
>        ;
>
> NOT     :       'not'
>        ;
> AND     :       'and'
>        ;
> OR      :       'or'
>        ;
> WORD    :       ('a'..'z' | '0'..'9' | '%' | '_')+
>        ;
> WS      :       (' ' | '\r' | '\n' | '\t')  { skip(); }
>        ;
>
> In ANTLRWorks I always get a MismatchedTokenException when trying to parse "not not or ljsdf". Parsing e.g. "not noti or ljsdf" works fine.
>
> I managed to get it working with quotation marks, but I would prefer to have a solution without.
>

-- 
Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox 3.5 -
sicherer, schneller und einfacher! http://portal.gmx.net/de/go/atbrowser


More information about the antlr-interest mailing list