Created
July 28, 2015 15:55
-
-
Save nadako/a10534a7c060c5294eae to your computer and use it in GitHub Desktop.
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(MyMacro.build()) | |
abstract MapItem(Array<Dynamic>) { | |
var itemId:Int; | |
var defId:String; | |
} | |
class Main { | |
static function main() { | |
var item = new MapItem(); | |
item.itemId = 10; | |
item.defId = "house"; | |
if (item.defId == "house") | |
trace(item.itemId); | |
} | |
} |
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.Context; | |
import haxe.macro.Expr; | |
import haxe.macro.Type; | |
using haxe.macro.Tools; | |
class MyMacro { | |
static function build():Array<Field> { | |
var fields = Context.getBuildFields(); | |
var newFields:Array<Field> = []; | |
var idx = 0; | |
for (field in fields) { | |
switch (field.kind) { | |
case FVar(fieldType, _): | |
field.kind = FProp("get", "set", fieldType); | |
field.access = [APublic]; | |
newFields.push({ | |
name: "get_" + field.name, | |
pos: field.pos, | |
access: [AInline], | |
kind: FFun({ | |
args: [], | |
ret: fieldType, | |
expr: macro return this[$v{idx}] | |
}), | |
}); | |
newFields.push({ | |
name: "set_" + field.name, | |
pos: field.pos, | |
access: [AInline], | |
kind: FFun({ | |
args: [{name: "value", type: fieldType}], | |
ret: fieldType, | |
expr: macro return this[$v{idx}] = value | |
}), | |
}); | |
idx++; | |
default: | |
// nothing to do here | |
} | |
} | |
var pos = Context.currentPos(); | |
newFields.push({ | |
name: "new", | |
pos: pos, | |
access: [APublic, AInline], | |
kind: FFun({ | |
ret: null, | |
args: [], | |
expr: macro this = untyped __new__(Array, $v{idx}), | |
}) | |
}); | |
return fields.concat(newFields); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment