Skip to content

Instantly share code, notes, and snippets.

@mockey
Created June 26, 2012 23:25
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 mockey/3000119 to your computer and use it in GitHub Desktop.
Save mockey/3000119 to your computer and use it in GitHub Desktop.
create class property from interface methods
package;
#if macro
import haxe.macro.Expr;
import haxe.macro.Context;
using Lambda;
using StringTools;
#end
#if !macro @:autoBuild(Macro.addProperties()) #end
interface IAutoProperty {}
class Macro {
#if macro
static var props:Array<{name:String, type:ComplexType}> = [];
#end
@:macro function addProperties():Array<Field> {
var cls = Context.getLocalClass().get();
if (cls.superClass != null)
return null;
var flds = Context.getBuildFields();
if (cls.isInterface) {
for (fld in flds) {
if (fld.name.startsWith("get_")) {
var t = switch (fld.kind) {
case FFun(f) : f.ret;
default: null;
}
if (t == null) continue;
var prop = fld.name.split("_").pop();
if (flds.exists(function(f) return f.name == "set_" + prop))
props.push({name: prop, type: t});
}
}
return null;
}
else {
for (prop in props) flds.push({
access: [APublic],
name: prop.name,
kind: FProp("get_" + prop.name, "set_" + prop.name, prop.type),
meta: [], pos: Context.currentPos(), doc: null
});
return flds;
}
}
}
interface ITest implements IAutoProperty {
private function get_name():String;
private function set_name(val:String):String;
}
package;
class Test implements ITest {
static function main() {
new Test();
}
function new() {
name = "Jonas";
trace(name);
}
function get_name():String {
return "getter: " + name;
}
function set_name(val:String):String {
return name = val + " from setter";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment