Skip to content

Instantly share code, notes, and snippets.

@fal-works
Created March 8, 2020 09:58
Show Gist options
  • Save fal-works/70f1615182d34dc98e2f10b81528ff6c to your computer and use it in GitHub Desktop.
Save fal-works/70f1615182d34dc98e2f10b81528ff6c to your computer and use it in GitHub Desktop.
Haxe build macro sample: adding method
#if macro
import haxe.macro.Context;
import haxe.macro.Expr;
import haxe.macro.TypeTools;
class MethodBuilder {
public static function build(): Array<Field> {
final fields = Context.getBuildFields();
final localType = Context.getLocalType();
if (localType == null) throw "Oh no";
final thisType = TypeTools.toComplexType(localType);
final parameterType = switch localType {
case TInst(_, [p]):
TypeTools.toComplexType(p);
default: return null;
}
final pos = Context.currentPos();
final myFunction: Function = {
expr: macro {
$i{"this"}.myVar = myArg;
return $i{"this"};
},
ret: (macro:$thisType),
args: [{ name: "myArg", type: (macro:Int)}]
};
final setMethod: Field = {
name: "myFunc",
access: [
Access.APublic,
Access.AInline
],
kind: FieldType.FFun(myFunction),
pos: pos,
};
fields.push(setMethod);
return fields;
}
}
#end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment