Skip to content

Instantly share code, notes, and snippets.

@back2dos
Last active December 15, 2015 16:49
Show Gist options
  • Select an option

  • Save back2dos/5291704 to your computer and use it in GitHub Desktop.

Select an option

Save back2dos/5291704 to your computer and use it in GitHub Desktop.
Getting constant values of expressions at macro time.
package ;
import haxe.macro.Expr;
import haxe.macro.Context;
class Interp {
static function error(pos:Position, ?msg = 'Constant value expected'):Dynamic
return Context.error(msg, pos);
static function const(c:Constant, pos):Dynamic
return
switch (c) {
case CInt(v): Std.parseInt(v);
case CFloat(f): Std.parseInt(f);
case CString(s): s;
case CIdent('null'): null;
case CIdent('true'): true;
case CIdent('false'): false;
case CIdent(_): error(pos);
case CRegexp(r, opt): new EReg(r, opt);
}
static public function eval(e:Expr):Dynamic
return
switch (e.expr) {
case EConst(c): const(c, e.pos);
case EParenthesis(e): eval(e);
case EObjectDecl(fields):
var ret:Dynamic = { };
for (f in fields)
Reflect.setField(ret, f.field, eval(f.expr));
ret;
case EArrayDecl(values): [for (v in values) eval(v)];
case ECheckType(e, _): eval(e);//there's no syntax for this, so if it appears, it's merely noise left behind by some other macro
default: error(e.pos);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment