[antlr-interest] AST rewrites for recursive rules
Phil Goodwin
phil.goodwin at gmail.com
Sat Sep 2 00:59:12 PDT 2006
I'm building a grammar for a language that is loosely based on the Java
example grammar in v3. I liked the way methodDeclaration was defined
recursively so I wrote a toy parser to see if I could use it to build an
AST. I hunted around in the documentation and examples but I couldn't find
the syntax I needed in order to access the tree returned by a referenced
rule, so I decided to try and see if I could implement it using actions. I
started with a recognizer:
methodDeclaration
: TYPE IDENTIFIER ':' methodDeclaratorRest
;
methodDeclaratorRest
: formalParameters?
;
formalParameters
: TYPE formalParameterDeclsRest
;
formalParameterDeclsRest
: IDENTIFIER (',' formalParameters)*
;
TYPE
: '<type''0'..'9''>'
;
IDENTIFIER
: '<Identifier''0'..'9''>'
;
When I started writing the AST code the first thing I thought was that I'd
need to make the parse iterative instead of recursive, but I'm a stubborn
sort and I liked the recusive algorithm. So I set out to just add the AST
generation code. What I ended up with takes this input:
<type0><Identifier0>:<type1><Identifier1>,<type2><Identifier2>,<type3><Identifier3>
and generates a tree that looks like this:
tree: (METHOD <Identifier0> <type0> (PARAMETERS (<type1> <Identifier1>)
(<type2> <Identifier2>) (<type3> <Identifier3>)))
I've pasted the code below. Here's my question: is there a better way to
access and manipulate the tree generated by a referenced rule? The AST
generation code below mirrors the elegance of the original recognizer but
that is lost amid the brutality done to the returned trees.
methodDeclaration
: t=TYPE i=IDENTIFIER ':' r=methodDeclaratorRest
-> ^(METHOD $i $t $r)
;
methodDeclaratorRest
: formalParameters?
-> ^(PARAMETERS formalParameters?)
;
formalParameters
: t=TYPE r=formalParameterDeclsRest
-> {((Tree)r.getTree()).getChildCount() > 1}? ^($t
{((BaseTree)r.getTree()).deleteChild(0)}) $r
-> ^($t $r)
;
formalParameterDeclsRest
: i=IDENTIFIER
(',' f=formalParameters -> $i $f
| -> $i
)
;
TYPE
: '<type''0'..'9''>'
;
IDENTIFIER
: '<Identifier''0'..'9''>'
;
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20060902/f17577c5/attachment.html
More information about the antlr-interest
mailing list