I examine heterogeneous trees in ANTLR (using ANTLRWorks 1.4.2).
Here is the example of what I have already done in ANTLR.
grammar test;
options {
language = java;
output = AST;
}
tokens {
PROGRAM;
VAR;
}
@members {
class Program extends CommonTree {
public Program(int ttype) {
token = new CommonToken(ttype, "<start>");
}
}
}
start
: program var function
// Works fine:
//-> ^(PROGRAM program var function)
// Does not work (described below):
-> ^(PROGRAM<Program> program var function)
;
program
: 'program'! ID ';'!
;
var
: TYPE^ ID ';'!
;
function
: ID '('! ')'! ';'!
;
TYPE
: 'int'
| 'string'
;
ID
: ('a'..'z' | 'A'..'Z')+
;
WHITESPACE
: (' ' | '\t' '\n'| '\r' | '\f')+ {$channel = HIDDEN;}
;
Sample input:
program foobar;
int foo;
bar();
When I use rewrite rule ^(PROGRAM<Program> program var function)
, ANTLR stumbles over and I get AST like this:
Whereas when I use this rewrite rule ^(PROGRAM program var function)
it works:
Could anyone explain where am I wrong, please? Frankly, I do not really get the idea of heterogeneous trees and how do I use
<…>
syntax in ANTLR.What do
r0
andr1
mean (first picture)?
< ... >
inside rewrite rules: you have eitheroutput=AST;
oroutput=template;
defined in theoptions{...}
section, not both. So you either generate an AST, or are generating (source) code with the StringTemplate engine. What exactly are you tying to do here anyway? What is your goal? – Bart Kiers<…>
and rewrite rules. My goal is to build heterogeneous AST (as the part of assignment). As far as I understand (it is tricky!), I have to implement my own tree and AST nodes. NoJava
code is necessary at this point (except for the code in the@members
section). Spent two days, no luck so far. – Little Jeans< ... >
in combination withoutput=template
. Thanks for the link. I don't have time at the moment to go through it, but I will later on (tomorrow probably) and get back to you. – Bart Kiers< ... >
is only used in chapter 9, Generating Structured Text with Templates and Grammars, where you need to setoutput=template
in the options section. This new feature isn't handled, AFAIK. – Bart Kiers