[antlr-interest] Re: Example for Micheal (was: When does AST construction go through
factory?)
Daniel Gackle
gackle at shaw.ca
Fri Jan 17 23:38:40 PST 2003
Micheal,
While we're at it, I just ran into a third problem. I added a class called
IntNode to the calc.g example from my previous post, and changed the "atom"
rule to do this:
atom: INT<AST=IntNode>;
In other words I made what I believe you referred to as a "per-tokenref
mapping". The generated code looks right:
tmp6_AST = (IntNode) astFactory.create(LT(1), "IntNode");
But it generates a run time exception: "System.InvalidCastException:
Specified cast is not valid." Keep in mind that in order to get this to
compile I had to get astFactory.create() to accept LT(1) as an int. To do
this I added the following temporary workaround code to ASTFactory.cs:
/// <summary>Added by dg</summary>
public static implicit operator int(Token t)
{
return t.Type;
}
That's all for now. Below is the full text of the "modified modified
calc.g".
Daniel
///////////////////////////////////////////////////
// Start of modified Calc.g ver.2
options {
language = "CSharp";
}
class CalcParser extends Parser;
options {
buildAST = true; // uses CommonAST by default
}
tokens {
EXPR<AST=ExprNode>;
STAR<AST=StarNode>;
}
{
public class StarNode { }
public class ExprNode { }
public class IntNode { }
}
expr
: mexpr (PLUS^ mexpr)* SEMI!
{ ## = #(#[EXPR,"EXPR"], ##); }
;
mexpr
: atom (STAR^ atom)*
;
atom: INT<AST=IntNode>
;
class CalcLexer extends Lexer;
WS : (' '
| '\t'
| '\n'
| '\r')
{ _ttype = Token.SKIP; }
;
LPAREN: '('
;
RPAREN: ')'
;
STAR: '*'
;
PLUS: '+'
;
SEMI: ';'
;
protected
DIGIT
: '0'..'9'
;
INT : (DIGIT)+
;
class CalcTreeWalker extends TreeParser;
expr returns [float r]
{
float a,b;
r=0;
}
: #(PLUS a=expr b=expr) {r = a+b;}
| #(STAR a=expr b=expr) {r = a*b;}
| i:INT {r = Convert.ToSingle(i.getText());}
;
// End of modified Calc.g ver.2
///////////////////////////////////////////////////
Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/
More information about the antlr-interest
mailing list