[antlr-interest] Syntactic Predicate gating and @init

Gavin Lambert antlr at mirality.co.nz
Sat Apr 19 19:38:40 PDT 2008


At 14:14 20/04/2008, Christian Schladetsch wrote:
>No. Most of my work is done in actions, yes. But there are places 
>(like compound blocks, arg lists etc) that need to change the 
>scope. That has to be done in @init before the subrules are 
>matched at all. Otherwise the subrules write their code to the 
>wrong scope.

Action blocks can appear wherever you want -- if you put one 
before the subrules, then it executes before the subrules.

In fact, the main difference between this:

rule
@init { foo(); }
   : subrule { bar(); }
   ;

And this:

rule
   : { foo(); } subrule { bar(); }
   ;

is that in the former case foo() will always be called, while in 
the latter case foo() will only be called if not 
predicting/backtracking, which sounds like what you want.

The problem with this latter approach is that if you *don't* have 
global backtracking enabled (ie. if it's possible for "subrule" to 
throw a 'failed match' exception during main parsing, not 
prediction), then you'll end up with foo() being called and bar() 
not, which will break your stack -- as the former approach does 
regardless of backtracking.  (Though from what you've said earlier 
I'm assuming that you do have backtracking on, so this may not be 
an issue for you.)

There's also a @finally block you can use to execute code when 
leaving the rule, regardless of success or failure; so if you do 
want to keep using @init then you should probably use @finally as 
well.  (Although, I think I remember Jim saying something about 
that not being supported by all target languages...?)

>Maybe I'm DoingItWrong, but the solution I found was:

I'm curious: is there some reason why you don't want to use 
ANTLR's built in stacked scopes?



More information about the antlr-interest mailing list