[antlr-interest] Problems with templates
Kevin Jackson
foamdino at gmail.com
Wed Jan 19 22:48:15 PST 2011
Hi,
I'm parsing some text and spitting out xml and I've chosen to do this
using output=template, rather than outputting AST and walking the
tree.
I've nearly got everything working, but I have a small problem with
nested templates inside a rewrite rule:
grammar:
----
//parser
game: (h+=hd)+ (m+=pl)+ -> game(infos={$h},plays={$m});
hd:
LEFT_SQUARE (info=STRING) (value=QUOTED_TEXT) RIGHT_SQUARE NEWLINE+
-> head(i={$info.text},v={$value.text})
;
pl: (num=DIGIT+) DOT (p1m=SAN) (p2m=SAN) NEWLINE* (ct=COMMENT_TEXT)*
-> play(num={$num.text}, p1m={$p1m.text}, p2m={$p2m.text},
comment={$ct})
| (num=DIGIT+) THREEDOTS (p1m=SAN) NEWLINE* -> play(num={$num.text},
p1m={$p1m.text})
;
//pl is b0rked somehow?
cm:
(c=COMMENT_TEXT) -> comment(c={$c.text})
;
//lexer
DIGIT: '0'..'9';
STRING: ('a'..'z'|'A'..'Z')+;
QUOTED_TEXT:
'"' .+ '"' {setText(getText().substring(1, getText().length()-1));}
;
COMMENT_TEXT:
'{' .+ '}' {setText(getText().substring(1, getText().length()-1));}
;
THREEDOTS: '...';
NEWLINE: '\r'? '\n' ;
DOT: '.';
LEFT_SQUARE: '[';
RIGHT_SQUARE: ']';
SAN: STRING DIGIT;
WS: (' '|'\t')+ {skip();};
----
template:
----
game(moves) ::= <<
\<game>
\<info>
<infos; separator="\n">
\</info>
\<begin>
\</begin>
\<moves>
<plays; separator="\n">
\</moves>
\</game>
>>
play(num, p1m, p2m, comment) ::= <<
\<ply side="1" pgn="" an="<p1m>-<p2m>"\>
\<pmv sr="1" sc="2" er="3" ec="2"/\>
<comment; separator="\n">
\</ply>
>>
comment(c) ::= <<
\<comment>
<c>
\</comment>
>>
head(i,v) ::= "\<<i>\><v>\</<i>\>"
---
output:
[java] <moves>
[java] <ply side="1" pgn="" an="e4-c5">
[java] <pmv sr="1" sc="2" er="3" ec="2"/>
[java] </ply>
[java] <ply side="1" pgn="" an="Nf3-d6">
[java] <pmv sr="1" sc="2" er="3" ec="2"/>
[java] </ply>
[java] <ply side="1" pgn="" an="d4-cxd4">
[java] <pmv sr="1" sc="2" er="3" ec="2"/>
[java] </ply>
[java] <ply side="1" pgn="" an="Nxd4-Nf6">
[java] <pmv sr="1" sc="2" er="3" ec="2"/>
[java] </ply>
[java] <ply side="1" pgn="" an="Nc3-Nc6">
[java] <pmv sr="1" sc="2" er="3" ec="2"/>
[java] [@103,382:406='Test comment',<12>,20:0] <-- this should be
<comment>Test comment</comment>
[java] </ply>
[java] </moves>
I think the issue is with the grammar for the rewrite rule rather than
with the template (which looks fine to me). The comment::= <<
template isn't being called and instead I'm getting an object
reference dumped into my play::= << template
Thanks,
Kev
More information about the antlr-interest
mailing list