[antlr-interest] question on greedy matching
Andrei Alexandrescu
andrei at metalanguage.com
Tue Oct 18 19:08:21 PDT 2005
Hello,
I have a question on how to solve a particular greedy/non-greedy
matching with ANTLR.
Consider the following language design for a sort of a try statement:
try statement ( catch (ID ID) '{' statement '}' )+
Clearly not an award-winning design, because it has the "dangling catch"
ambiguity:
try
try
foo();
catch (E1 e) { bar(); }
catch (E2 e) { baz(); }
There's a need for a meta-rule to decide where the last catch comes. So
here it is:
"One catch always binds to the closest try statement. The others always
bind to the outermost try statement possible."
I'm not sure I was clear enough, but the intent of the rule above binds
the first catch in the example to the inner try, and the second catch to
the outer try, as the indentation suggests.
Moreover, in the example:
try
try
foo();
catch (E1 e) { bar(); }
catch (E2 e) { baz(); }
catch (E3 e) { baa(); }
again the rule makes the statements bind as the indentation suggests.
So, the question is, what would be the cleanest way to express that in
ANTLR (preferrably without semantic predicates)? If I understand
correctly, it's not an issue of setting the greedy option, because the
same try construct must be parsed greedily or not, depending on whether
the parent is a try statement as well.
Thanks,
Andrei
More information about the antlr-interest
mailing list