Skip to content

Instantly share code, notes, and snippets.

@anissen
Forked from ibilon/GenNew.hx
Last active February 23, 2016 12:14
Show Gist options
  • Save anissen/6852cf036a3d7745fb71 to your computer and use it in GitHub Desktop.
Save anissen/6852cf036a3d7745fb71 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;
}
}
Run:
haxe -main Test -x Test
Output:
Test.hx:7: 19,hello macro
@:build(GenNew.build())
class NoConstructor {
@:param public var i(default, null):Int;
@:param private var s:String;
public function show() {
trace(i, s);
}
}
class Test {
public static function main() {
var obj = new NoConstructor(19, "hello macro");
obj.show();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment