I am trying to create a heterogeneous tree based on a sample provided here: http://www.antlr.org/wiki/display/ANTLR3/Tree+construction#Treeconstruction-Heterogeneoustreenodes
I have created a grammar file as follows:
grammar T;
options {
language=CSharp3;
ASTLabelType=CommonTree;
output=AST;
TokenLabelType=CommonToken;
k=3;
}
tokens {
ROOT;
UNARY_MIN;
}
@lexer::header
{
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using ANTLRSandbox.Criteria;
}
@parser::header
{
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using ANTLRSandbox.Criteria;
}
@parser::namespace { ANTLRSandbox }
@lexer::namespace { ANTLRSandbox }
public
parse
: exp EOF -> ^(ROOT<RootNode> exp)
;
exp
: addExp
;
addExp
: mulExp (('+'<PlusNode> | '-'<MinusNode>)^ mulExp)*
;
mulExp
: unaryExp (('*' | '/')^ unaryExp)*
;
unaryExp
: '-' atom -> ^(UNARY_MIN atom)
| atom
;
atom
: Number
| '(' exp ')' -> exp
;
Number
: ('0'..'9')+ ('.' ('0'..'9')+)?
;
Space
: (' ' | '\t' | '\r' | '\n'){Skip();}
;
And the node classes looks like this:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Antlr.Runtime;
using Antlr.Runtime.Tree;
namespace ANTLRSandbox.Criteria
{
public class RootNode : CommonTree
{
public RootNode(int ttype) { }
public RootNode(int ttype, IToken t) { }
public RootNode(IToken t) { }
}
}
Classes PlusNode
and MinusNode
are identical with RootNode
, so I won't post them here.
And here is how I create the actual tree:
string s = "(12.5 + 56 / -7) * 0.5";
ANTLRStringStream Input = new ANTLRStringStream(s);
TLexer Lexer = new TLexer(Input);
CommonTokenStream Tokens = new CommonTokenStream(Lexer);
TParser Parser = new TParser(Tokens);
TParser.parse_return ParseReturn = Parser.parse();
CommonTree Tree = (CommonTree)ParseReturn.Tree;
The code runs without any error, but when I 'watch' for Tree
object, all its nodes are CommonTree
type and all breakpoints I have placed in PlusNode
, MinusNode
, RootNode
constructors are missed.
I have followend the sample provided in ANTLR3 wiki page and I couldn't find any sample on the web. I know they intend to drop this approach at some point (found this on ANTLR3 preview notes) but this implementation suits me better (I need to create different objects types based on grammar context).
So ... any hints? Am I missing something? Some option/flag to put it into grammar definition file?
Thanks! D.