Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Class<T> of Context.getLocalClass() in build macro

Tags:

macros

haxe

I want to make a macro that adds a field to my classes, and the field value should be Class<T> of class they are sitting in. Here is my minimal example, and it does not compile with this error:

src/Base.hx:3: characters 2-11 : Unknown identifier : foo.Foo

But if I move Foo from package foo to root package, then it compiles and works.

Main.hx

import foo.Foo;
class Main 
{
    static function main() 
    {
        trace(Foo.data);
    }
}

Build.hx

import haxe.macro.Context;
import haxe.macro.Type;
import haxe.macro.Expr;

class Build
{
    macro static public function build(DataClass):Array<Field> 
    {
        var cls = Context.getLocalClass().get();
        var pack = cls.pack.concat([cls.name]);
        var name = pack.join(".");
        trace(name);

        var expr = {
            expr: ExprDef.EConst(Constant.CIdent(name)),
            pos: Context.currentPos()
        }

        var newFieldCls = macro class {

            public static var data:Class<Dynamic> = $expr; 

        }

        var fields = Context.getBuildFields();
        return fields.concat(newFieldCls.fields);


    }
}

Base.hx

package;

@:autoBuild(Build.build(Main.Data))
class Base
{
    public function new()
    {
    }
}

foo/Foo.hx

package foo;

class Foo extends Base
{
}
like image 731
romamik Avatar asked Apr 18 '16 11:04

romamik


1 Answers

EConst(CIdent("foo.Bar")) won't work, because that's very much as if you could specify a name with . periods in it. Instead, you need to do EField({ expr: EConst(CIdent("foo")) }, "Bar"), since that is what foo.Bar gets parsed to by a compiler itself (try traceing expressions from a macro).

So the correct code would be

import haxe.macro.Context;
import haxe.macro.Expr;
class Build {
    public static macro function build():Array<Field> {
        var self = Context.getLocalClass().get();
        var cpos = Context.currentPos();
        var out:Expr = null;
        inline function add(name:String) {
            if (out == null) {
                out = { expr: EConst(CIdent(name)), pos: cpos };
            } else out = { expr: EField(out, name), pos: cpos };
        }
        for (name in self.pack) add(name);
        add(self.name);
        return Context.getBuildFields().concat((macro class {
            public static var data:Class<Dynamic> = $out;
        }).fields);
    }
}

handling creation of a EConst(CIdent) expression and subsequent wrapping it in EField layers for trailing packages, and, finally, the class name.

like image 197
YellowAfterlife Avatar answered Sep 27 '22 19:09

YellowAfterlife