[antlr-interest] parse error because of AST rewrite rules?
Stefan Oestreicher
so at deluxe-design.at
Mon Sep 21 11:07:08 PDT 2009
Hi,
I'm working on a grammar for a simple programming language and I'd like
to support variable declarations like that:
int a, b = 3
I started out with the following rule:
variableDeclaration
: type ID ( COMMA ID )* ( ASSIGN expression )?
;
Now I'd like to generate an AST for the above example that looks like that:
^(VAR_DEF int a)
^(VAR_DEF int b)
^(= a 3)
^(= b a)
So I've tried it with the following rules:
--- grammar snippet ---
variableDeclaration
: simpleVariableDeclaration
| listVariableDeclaration
;
simpleVariableDeclaration
: type ID ( ASSIGN expression )?
-> ^(VAR_DEF ID type)
^(ASSIGN ID expression)?
;
listVariableDeclaration
: type first=ID ( COMMA other+=ID )+
listVariableAssignment[$first, $other]?
-> ^(VAR_DEF $first type)
^(VAR_DEF $other type)
listVariableAssignment?
;
listVariableAssignment[pANTLR3_COMMON_TOKEN first, pANTLR3_VECTOR other]
: ASSIGN expression
-> ^(ASSIGN {$first} expression)
^(ASSIGN {$other} {$first})+
;
--- /grammar snippet ---
I've also tried this simpler variant for listVariableDeclaration:
--- grammar snippet ---
listVariableDeclaration
: ( type first=ID ( COMMA other+=ID )+
-> ^(VAR_DEF $first type)
^(VAR_DEF $other type)
)
( ASSIGN expression
-> ^(ASSIGN $first expression)
^(ASSIGN $other $first)+
)?
;
--- /grammar snippet ---
The modified rules still produce a correct parse tree in the interpreter
but the generated code raises a parse error. It either complains about
the assignment operator after the ID list or about the semicolon the
terminates the declaration (not shown in the example).
If I remove the rewrite rules there is no problem.
I'd appreciate any hint about what I'm doing wrong. I'm using the C
target btw, version 3.1.3.
Thanks,
Stefan
More information about the antlr-interest
mailing list