Skip to content

Instantly share code, notes, and snippets.

@hotpotato
Created January 20, 2011 22:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hotpotato/788833 to your computer and use it in GitHub Desktop.
Save hotpotato/788833 to your computer and use it in GitHub Desktop.
-main Main
-neko main.n
package ;
interface Car
{
public function doIt():Void;
}
class Main
{
public static function main():Void
{
var c:Car = MyMacro.createMyCarClass().createCar();
c.doIt();
}
}
package ;
#if macro
import haxe.macro.Context;
import haxe.macro.Type;
import haxe.macro.Expr;
import neko.FileSystem;
import neko.io.File;
#end
class MyMacro
{
@:macro public static function createMyCarClass()
{
// we create a class file on the fly ;)
// this is just a simple way to create it
trace("create MyCar class file");
var input = File.write("MyCar.hx", false);
input.writeString(
'
import Main.Car;
class MyCar implements Car {
public static function createCar () { return new MyCar();}
public function new () {}
public function doIt():Void trace("Interface implemented on the fly")
}');
input.close();
trace("parse and type my created MyCar class");
Context.getType("MyCar");
trace("after get MyCar");
trace("delete MyCar class file");
FileSystem.deleteFile("MyCar.hx");
// return the class, but you can also return a factory or whatever
return { expr:EConst(CType("MyCar")), pos:Context.currentPos() };
}
}
@TheHippo
Copy link

You could do @:macro class MyMacro. Then the whole only exists during compile time...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment