Skip to content

Instantly share code, notes, and snippets.

@kevinresol
Last active January 2, 2024 06:31
Show Gist options
  • Save kevinresol/84e6f214430347112b7c to your computer and use it in GitHub Desktop.
Save kevinresol/84e6f214430347112b7c to your computer and use it in GitHub Desktop.
Copy expressions with Haxe macro
(function (console) { "use strict";
var Main = function() { };
Main.main = function() {
console.log("simple copy");
var myFunc = function() {
var sum = 0;
var k = 1;
};
console.log("customize");
var k1 = 1;
};
Main.main();
})(typeof console != "undefined" ? console : {log:function(){}});
package;
import haxe.macro.Context;
using haxe.macro.ExprTools;
using Lambda;
class Macro
{
/**
Copy some contents from a Type
**/
public static macro function copyExprFrom(typeName:String, methodName:String)
{
// get the Type
var inst = switch Context.getType(typeName)
{
case TInst(i,_): i.get();
default: throw "";
}
// extract the field we needed
var field = inst.statics.get().find(function(s) return s.name == methodName);
// this creates a special expr (just a meta if you inspect it) which
// will be replaced by the stored TypedExpr (field.expr() in this case)
var e = Context.storeTypedExpr(field.expr());
return e;
}
/**
Extract some contents from a type similarly to above.
But instead of copying it directly, here the contents are modified
**/
public static macro function customize()
{
// get the Type
var inst = switch Context.getType('Test')
{
case TInst(i,_): i.get();
default: throw "";
}
// get the field
var field = inst.statics.get().find(function(s) return s.name == 'test');
// convert the TypedExpr to Expr
var e = Context.getTypedExpr(field.expr());
// now you can trasform the expression at will
// here I simply grab the last expression and return it
switch e
{
case macro function ():$r $b{b}: // assuming the expr is a function and the function body is a block
return b.pop(); // get the last expr in the function body
default: throw "";
}
}
}
package;
class Main {
public static function main()
{
trace("simple copy");
var myFunc = Macro.copyExprFrom('Test', 'test');
trace("customize");
Macro.customize();
}
}
package;
class Test
{
public static function test()
{
var sum = 0;
var k = 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment