Can't find how to write non symmetrical grammar rule

16 views
Skip to first unread message

Bruno M

unread,
Apr 9, 2013, 5:23:29 AM4/9/13
to antlr-di...@googlegroups.com
Hello,
I'm using ANTLR 3.1.3.
I've been struggling with the following problem.

In my grammar, I need to be able to parse expressions which abide by the following rules:

- the expression is composed of 4 distinct terms (I'll name them a b c d for the sake of the explanation).
- each term is optional
- there must be at least one of the terms in the expression
- each term must appear one time at most
- the order of the terms must be respected (a comes first, then b, etc.)
- when there are more than one term, two adjacent terms are separated by ';'

Valid examples:
a
a;b
a;c
a;c;d
b;d

Invalid examples:
<empty>
ab
a;a;b
b;a

I can of course describe all possibilities in my grammar. With only four terms, the number of cases is still limited. However, on the principle I think it would be interesting to find a way to efficiently describe my grammar in a scalable way (scalable in terms of the number of terms in my expression).

The help of an experimented person would be most welcome!
Thanks a lot,
Bruno

Mike Lischke

unread,
Apr 9, 2013, 8:07:36 AM4/9/13
to antlr-di...@googlegroups.com

Bruno,

> - the expression is composed of 4 distinct terms (I'll name them a b c d for the sake of the explanation).
> - each term is optional
> - there must be at least one of the terms in the expression
> - each term must appear one time at most
> - the order of the terms must be respected (a comes first, then b, etc.)
> - when there are more than one term, two adjacent terms are separated by ';'


Basically the expression is simple:

rule: (a ';')? (b ';')? (c ';')? (d ';')? { xxx };

The action xxx at the end of the expression just has to remove the last semicolon. Your requirement to have at least one term in the expression is void, since if there's none of the 4 terms the entire rule wouldn't match anyway. If this rule is required however then use an empty alternative and throw a recognition error.

Mike
--
www.soft-gems.net

bruno.m...@gmail.com

unread,
Apr 9, 2013, 8:42:45 AM4/9/13
to antlr-di...@googlegroups.com, mike.l...@googlemail.com
Thanks for the tip Mike.
As I'm completely new to ANTLR, would you go as far as suggesting how I can remove the last semi-colon from the rule by means of an xxx expression?
(it is not quite clear to me, as the parser is supposed to analyse an existing string. So if the string does not contain the semi-colon, which it is not supposed to, then the rule will just not apply, as it expects a semi-colon, won't it?)
Reply all
Reply to author
Forward
0 new messages