Skip to content

Instantly share code, notes, and snippets.

@mcheshkov
Last active October 10, 2016 19:29
Show Gist options
  • Save mcheshkov/873a280a9b5beac75ef31ee6f8c40163 to your computer and use it in GitHub Desktop.
Save mcheshkov/873a280a9b5beac75ef31ee6f8c40163 to your computer and use it in GitHub Desktop.
package;
import haxe.macro.Context;
import haxe.macro.Expr;
import haxe.macro.Type;
class ExtendMacro {
#if macro
static function buildExtend(reference:Expr, fieldsObj:Expr){
var fields:Array<{ field : String, expr : Expr }> = [];
switch(fieldsObj.expr){
case ExprDef.EObjectDecl(fs):
fields = fs.copy();
case _: Context.error("unexpected type for fields", Context.currentPos());
}
var t:Type = haxe.macro.Context.typeof(reference);
switch(t){
case TType(tt, ps):
var td:DefType = tt.get();
switch (td.type){
case TAnonymous(ar):
var a = ar.get();
for (f in a.fields){
var name:String = f.name;
var found = Lambda.find(fields, function(f2){
return f2.field == name;
});
if (found == null){
fields.push({
field: name,
expr: macro $reference.$name
});
}
}
case _: throw "unexpected type for typedef: " + td.type;
}
case _: throw "unexpected type: " + t;
}
var objE = {expr: ExprDef.EObjectDecl(fields), pos: Context.currentPos()};
return objE;
}
#end
macro public static function extend(reference:Expr, fieldsObj:Expr){
return buildExtend(reference, fieldsObj);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment