Skip to content

Instantly share code, notes, and snippets.

@ibilon
Last active February 23, 2016 12:13
Show Gist options
  • Save ibilon/bc420d498f39f3742416 to your computer and use it in GitHub Desktop.
Save ibilon/bc420d498f39f3742416 to your computer and use it in GitHub Desktop.
Object construction with macro
import haxe.macro.Expr;
import haxe.macro.Context;
class GenNew
{
macro public static function build () : Array<Field>
{
var fields = Context.getBuildFields();
var args = [];
var assigns = [];
for (field in fields)
{
for (meta in field.meta)
{
if (meta.name == ":param")
{
switch (field.kind)
{
case FVar(t, e), FProp(_, _, t, e):
args.push({
name: field.name,
type: t,
opt: false
});
var name = field.name;
assigns.push(macro this.$name = $i{name});
default:
}
}
}
}
var f = {
kind: FFun({
args: args,
expr: {
expr: EBlock(assigns),
pos: Context.currentPos()
},
params: [],
ret: null
}),
name: "new",
pos: Context.currentPos(),
access: [APublic]
};
fields.push(f);
return fields;
}
}
@:build(GenNew.build())
class Test
{
@:param public var i(default, null):Int;
@:param private var s:String;
public function show ()
{
trace(i, s);
}
public static function main ()
{
var obj = new Test(19, "hello macro");
obj.show();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment