[antlr-interest] how to define post rule code

Loring Craymer Loring.G.Craymer at jpl.nasa.gov
Sun Aug 7 14:05:33 PDT 2005


ANTLR 2.x generates code "in order"--actions placed after a token (or rule)
to be matched generate code that is after the code for matching and AST node
construction for that token.  The "init" code is to overcome scoping
problems:  if you use syntactic predicates, actions are enclosed in
if (guessing == 0) {
	<action code>
} 

Which, of course, makes any declarations inside the if block have a scope
that is limited to the current action.  "init" code is not wrapped by an if
(guessing) {} statement and is visible throughout the rule.

So just put your "post" actions at the end of the rule (but watch out for
alternative blocks:  A | B | C { foo(); } only executes foo() if C is
matched.  ( ( A | B | C ) { foo() } executes foo after any of the
alternatives).

--Loring

> -----Original Message-----
> From: antlr-interest-bounces at antlr.org [mailto:antlr-interest-
> bounces at antlr.org] On Behalf Of Li Xu
> Sent: Tuesday, July 26, 2005 12:11 PM
> To: antlr-interest at antlr.org
> Subject: [antlr-interest] how to define post rule code
> 
> Hi,
> 
> I am using the ANTLR Java. My question is how does one define the java
> code
> to be executed after all the generated rule code. For example, I have code
> block
> {...//foo } and rule:
> bar {any java initialization code}: ...rule_body ...;
> 
> The generated code I need is like:
> public void bar() {
>   ...//the generated ANTLR parsing code
> 
>   {the foo block should be here, after all generated code}
> }
> 
> I have looked thru the manual, and one can add preamble code after the
> rule name
> (as shown above); however, I don't see anything about postamble--ie, the
> code
> one can attach to the very end --after all the generated parsing code.
> 
> So, my question is can this be done and how?
> 
> PS. I need this to manipulate the AST tree, so I can set returnAST to the
> tree I created in Java. Rightnow, the last line of code is
> returnAST=some_ast and is
> generated by antlr.
> 
> Thanks and greetings!
> Li Xu



More information about the antlr-interest mailing list