[antlr-interest] Newbie Q: Duplicating nodes from parse into AST

Austin Hastings Austin_Hastings at Yahoo.com
Mon Oct 1 16:36:21 PDT 2007


I'm trying to parse a c-like language. Right now I'm stuck trying to 
generate duplicate DECL nodes for "int i,j" type declarations. Here is 
the relevant bits of the grammar:

declaration
    : decl_type_spec
      decl_prefix_expr (',' decl_prefix_expr)*
      ';'
        -> ^(DECL decl_type_spec decl_prefix_expr)+
    ;

decl_type_spec
    : decl_type_item+
    ;

decl_type_item
    : STORAGE_CLASS
    | TYPE_QUALIFIER
    | BUILTIN_TYPE
    ;
   
decl_prefix_expr
    : decl_pointer decl_prefix_expr    -> ^(decl_pointer decl_prefix_expr)
    | decl_postfix_expr
    ;

decl_postfix_expr
    : decl_primary_expr
    ;

decl_primary_expr
    : IDENTIFIER
    | '(' decl_prefix_expr ')'
    ;

-----

My input is "int x, *y;"

Using AntlrWorks, the parse tree shows (correctly, IMO) that the text is 
parsed as

declaration:
    decl_type_spec -> decl_type_item -> "int"
    decl_prefix_expr -> decl_postfix_expr -> decl_primary_expr -> "x"
    ","
    decl_prefix_expr -> decl_pointer -> "*"
    ................. -> decl_prefix_expr -> decl_postfix_expr -> 
decl_primary_expr -> "y"
    ";"

To me, this should indicate that the rewrite rule in declaration has a 
single "decl_type_spec" and a list of two "decl_prefix_expr"s and it 
should generate

^(DECL int x)
^(DECL int *y)

But the AST view in AntlrWorks shows:

nil:
    ^(DECL int x)
    ^(DECL ^(* y))   # AKA:  DECL -> * -> y

Can anyone shed some light on this? Why isn't my decl_type_spec ("int") 
being repeated for the second DECL tree?

=Austin



More information about the antlr-interest mailing list