Skip to content

Instantly share code, notes, and snippets.

@whacked
Forked from devboy/ComponentMacro.hx
Created October 14, 2013 20:40
Show Gist options
  • Save whacked/6981820 to your computer and use it in GitHub Desktop.
Save whacked/6981820 to your computer and use it in GitHub Desktop.
package org.devboy.hxTask;
import neko.Lib;
import haxe.macro.Context;
import haxe.macro.Expr;
import haxe.macro.Type;
class ComponentMacro
{
private static var idCount = 0;
@:macro
public static function build(): Array<Field>
{
var pos = haxe.macro.Context.currentPos();
var mk = function( expr ) return {expr: expr, pos: pos};
var fields = haxe.macro.Context.getBuildFields();
var tint = TPath({ pack : [], name : "Int", params : [], sub : null });
fields.push( { name : "ID", doc : null, meta : [], access : [AStatic, APublic], kind : FVar(tint, {expr: EConst(CInt(Std.string(idCount))), pos: pos}) , pos: pos });
fields.push(
{
name: "id",
doc: null,
meta:[],
access: [APublic],
kind: FFun(
{
ret: tint, params: [], args: [], expr: mk( EReturn( mk( EConst(CInt(Std.string(idCount))))))
} ),
pos: pos
} );
idCount++;
return fields;
}
}
package org.devboy.hxTask;
import neko.Lib;
import haxe.macro.Expr;
import haxe.macro.Context;
import org.devboy.hxTask.ComponentMacro;
class Main
{
public static function main()
{
Lib.println( ComponentA.ID ); //0
Lib.println( new ComponentA().id() ); //0
Lib.println( new ComponentA().id() ); //0
Lib.println( ComponentB.ID ); //1
Lib.println( new ComponentB().id() ); //1
Lib.println( new ComponentB().id() ); //1
}
}
@:autoBuild( org.devboy.hxTask.ComponentMacro.build() )
interface Component
{
function id():Int;
}
class ComponentA implements Component
{
public function new()
{
}
}
class ComponentB implements Component
{
public function new()
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment