Skip to content

Instantly share code, notes, and snippets.

@hotpotato
Created December 21, 2010 23:50
Show Gist options
  • Save hotpotato/750837 to your computer and use it in GitHub Desktop.
Save hotpotato/750837 to your computer and use it in GitHub Desktop.
package;
import haxe.rtti.Meta;
interface TestInterface { }
interface TestClass implements TestInterface { }
class Main
{
static function getImplements (className:String) {
var rtti = Meta.getType(Main).rtti[0];
return Reflect.field(rtti, className);
}
static function main()
{
RttiMacro.generate();
trace(getImplements("TestClass"));
}
}
package ;
#if macro
import haxe.macro.Context;
import haxe.macro.Expr;
import haxe.macro.Type;
#end
class RttiMacro
{
#if macro
public static function toConstStringExpr (s:String, ?pos:Position) {
return toConstExpr(CString(s), pos);
}
public static function toConstExpr (c:Constant, ?pos:Position) {
return toExpr(EConst(c), pos);
}
public static function toExpr (expr:ExprDef, ?pos:Position) {
return { expr: expr, pos: pos == null ? Context.currentPos() : pos };
}
public static function toObjectExpr (fields:Array<{ field : String, expr : Expr }>, ?pos:Position) {
return toExpr(EObjectDecl(fields), pos);
}
public static function toArrayExpr (values:Array<Expr>, ?pos:Position) {
return toExpr(EArrayDecl(values), pos);
}
#end
@:macro public static function generate():Expr
{
var f = function (types:Array<Type>)
{
var result = [];
for ( t in types )
{
switch( t )
{
case TInst(c, _):
var info = c.get();
var interfaces = [];
for (i in info.interfaces) {
interfaces.push(toConstStringExpr(i.t.toString()));
}
var fullClassName = c.toString();
result.push( {field: fullClassName, expr:toArrayExpr(interfaces) });
default:
}
}
var mainClass = switch (Context.getType("Main")) { case TInst(c, _): c.get(); default: throw "Main not found"; };
mainClass.meta.add("rtti", [toObjectExpr(result)]);
};
haxe.macro.Context.onGenerate(f);
var nullExpr = EConst(CIdent("null"));
return { expr: nullExpr, pos:haxe.macro.Context.currentPos() };
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment