Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Main2.ASTTools.execute;
- import Main2.ASTTools.parse;
- import AST;
- class ASTTools
- {
- public static function execute(a:AST)
- {
- return switch(a)
- {
- case Number(n): n;
- case Sum(n1, n2): execute(n1) + execute(n2);
- case Mult(n1, n2): execute(n1) * execute(n2);
- }
- }
- macro public static function parse(e:haxe.macro.Expr)
- {
- return haxe.macro.Context.makeExpr(convertExpr(e), e.pos);
- }
- public static function convertExpr(e:haxe.macro.Expr):AST
- {
- return switch(e.expr)
- {
- case EConst(CFloat(n) | CInt(n)): Number(Std.parseFloat(n));
- case EBinop(OpAdd, e1, e2): Sum( convertExpr(e1), convertExpr(e2) );
- case EBinop(OpMult, e1, e2): Mult( convertExpr(e1), convertExpr(e2) );
- default: throw new haxe.macro.Expr.Error("Expression not supported", e.pos);
- }
- }
- }
- class Main2
- {
- static function main()
- {
- trace(execute( Sum( Mult(Number(20), Number(2)), Number(2) ) ));
- trace(execute( parse( 20 * 2 + 2 ) ));
- }
- }
- //file AST.hx
- enum AST
- {
- Number(n:Float);
- Sum(n1:AST, n2:AST);
- Mult(n1:AST, n2:AST);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement