Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Last active October 28, 2020 07:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshCheek/2fdaba7abdd22aac8c61 to your computer and use it in GitHub Desktop.
Save JoshCheek/2fdaba7abdd22aac8c61 to your computer and use it in GitHub Desktop.
Haxe macro to define functions.
$ haxe -cp zomg --interp -main Wat
// file: zomg/A.hx
package zomg;
class A {
public static function x() {
trace("this is a");
}
}
// file: zomg/B.hx
class B {
public static function x() {
trace("this is b");
}
}
import haxe.macro.Context;
import haxe.macro.Expr;
class MyMacro {
macro static function loadEm():Array<Field> {
var fields = Context.getBuildFields();
var calls = {
pos: Context.currentPos(),
expr: EBlock([
{ pos: Context.currentPos(),
expr: ECall({
pos: Context.currentPos(),
expr: EField({
pos: Context.currentPos(),
expr: EField({
expr: EConst(CIdent("zomg")),
pos: Context.currentPos(),
}, "A"),
}, "x"),
},
[]),
},
{ pos: Context.currentPos(),
expr: ECall({
pos: Context.currentPos(),
expr: EField({
pos: Context.currentPos(),
expr: EConst(CIdent("B")),
}, "x"),
},
[]),
}
]),
};
var c = macro class X {
public static function main() {
${calls};
}
};
fields.push(c.fields[0]);
return fields;
}
}
@:build(MyMacro.loadEm())
class Wat { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment