Created
January 6, 2013 23:09
-
-
Save alecmce/4470950 to your computer and use it in GitHub Desktop.
A failed attempt to automatically assign an ID to each type... What am I doing wrong?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package; | |
import massive.munit.Assert; | |
import haxe.macro.Expr; | |
import haxe.macro.Context; | |
class MacroTest | |
{ | |
@:macro public function addComponent(component:Dynamic) | |
{ | |
return macro addComponentWithID(component, MyMacro.getComponentID(component)); | |
} | |
function addComponentWithID(component:Dynamic, id:Int):Int | |
{ | |
trace(id + " => " + component); | |
return id; | |
} | |
@Test | |
public function twoInstancesOfTheSameTypeShareACommonID() | |
{ | |
var first = addComponent(new MacroExampleA()); | |
var second = addComponent(new MacroExampleA()); | |
Assert.areEqual(first, second); | |
} | |
@Test | |
public function differentTypesHaveDifferentIDs() | |
{ | |
var first = addComponent(new MacroExampleA()); | |
var second = addComponent(new MacroExampleB()); | |
Assert.areNotEqual(first, second); | |
} | |
@Test | |
public function stringsAlsoShareACommonID() | |
{ | |
var first = addComponent("hello"); | |
var second = addComponent("other"); | |
Assert.areNotEqual(first, second); | |
} | |
} | |
class MacroExampleA | |
{ | |
public function new() {} | |
} | |
class MacroExampleB | |
{ | |
public function new() {} | |
} | |
@:macro class MyMacro | |
{ | |
static var count = 0; | |
static var components:Array<Dynamic>; | |
public static function getComponentID(component:Expr):Expr | |
{ | |
if (components == null) | |
components = new Array<Dynamic>(); | |
var type = null; | |
switch (Context.typeof(component)) | |
{ | |
case TInst(typeRef, _): | |
type = typeRef.get().name; | |
default: | |
} | |
var index = -1; | |
for (i in 0...components.length) | |
{ | |
if (type == components[i]) | |
index = i + 1; | |
} | |
if (index == -1) | |
index = components.push(type); | |
return Context.makeExpr(index, component.pos); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment