Skip to content

Instantly share code, notes, and snippets.

@vizanto
Last active September 21, 2017 15:53
Show Gist options
  • Save vizanto/f19d72a6fc6b838ad2345b5fc29f3cec to your computer and use it in GitHub Desktop.
Save vizanto/f19d72a6fc6b838ad2345b5fc29f3cec to your computer and use it in GitHub Desktop.
This example shows a way to provide field name and types (without the need to fully qualify types) by abusing the Haxe type checking syntax as argument to a build macro.
import haxe.macro.Expr;
import haxe.macro.ExprTools;
import haxe.macro.Context;
class Macro {
static macro function addField (nameAndType : Expr) : Array<Field> {
var fieldName;
var ct;
switch nameAndType.expr {
default: throw "Please provide field name and type as (fieldName : Type)";
case EParenthesis({expr : ECheckType({expr: EConst(CIdent(name))}, path)}):
fieldName = name;
ct = path;
}
var fields = Context.getBuildFields();
var p = Context.currentPos();
var klass = macro class Field {
public var $fieldName (default, null) : $ct;
}
fields.push(klass.fields[0]);
return fields;
}
}
// haxe -x Main -D dump=pretty
@:directlyUsed @:used @:build(Macro.addField(((x : Null<Int64>))))
class Main {
public function new() {}
public var x(default,null):Null<haxe.Int64>;
@:keep
static function main() {
var main = new Main();
var this1 = new haxe._Int64.___Int64(0, 1);
main.x = @:implicitCast cast this1;
var tmp = haxe.Log.trace;
tmp(haxe._Int64.Int64_Impl_.toString(main.x), {fileName : "Main.hx", lineNumber : 9, className : "Main", methodName : "main"});
}
}
import haxe.Int64;
@:build(Macro.addField((x:Null<Int64>)))
class Main {
public function new() {}
static function main() {
var main = new Main();
main.x = 1;
trace(main.x); // Main.hx:9: 1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment