Last active
February 23, 2016 12:13
-
-
Save ibilon/bc420d498f39f3742416 to your computer and use it in GitHub Desktop.
Object construction with macro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@: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