Skip to content

Instantly share code, notes, and snippets.

@nadako
Created July 28, 2015 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nadako/a10534a7c060c5294eae to your computer and use it in GitHub Desktop.
Save nadako/a10534a7c060c5294eae to your computer and use it in GitHub Desktop.
@: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);
}
}
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