Advertisement
Guest User

simple AST example with macros + pattern matching

a guest
Feb 14th, 2013
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Haxe 1.13 KB | None | 0 0
  1. import Main2.ASTTools.execute;
  2. import Main2.ASTTools.parse;
  3. import AST;
  4.  
  5. class ASTTools
  6. {
  7.   public static function execute(a:AST)
  8.   {
  9.     return switch(a)
  10.     {
  11.       case Number(n): n;
  12.       case Sum(n1, n2): execute(n1) + execute(n2);
  13.       case Mult(n1, n2): execute(n1) * execute(n2);
  14.     }
  15.   }
  16.  
  17.   macro public static function parse(e:haxe.macro.Expr)
  18.   {
  19.     return haxe.macro.Context.makeExpr(convertExpr(e), e.pos);
  20.   }
  21.  
  22.   public static function convertExpr(e:haxe.macro.Expr):AST
  23.   {
  24.     return switch(e.expr)
  25.     {
  26.       case EConst(CFloat(n) | CInt(n)): Number(Std.parseFloat(n));
  27.       case EBinop(OpAdd, e1, e2): Sum( convertExpr(e1), convertExpr(e2) );
  28.       case EBinop(OpMult, e1, e2): Mult( convertExpr(e1), convertExpr(e2) );
  29.       default: throw new haxe.macro.Expr.Error("Expression not supported", e.pos);
  30.     }
  31.  
  32.   }
  33. }
  34.  
  35. class Main2
  36. {
  37.   static function main()
  38.   {
  39.     trace(execute( Sum( Mult(Number(20), Number(2)), Number(2) ) ));
  40.     trace(execute( parse( 20 * 2 + 2 ) ));
  41.   }
  42. }
  43.  
  44.  
  45. //file AST.hx
  46. enum AST
  47. {
  48.     Number(n:Float);
  49.     Sum(n1:AST, n2:AST);
  50.     Mult(n1:AST, n2:AST);
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement