Nathan
Nathan

Reputation: 7709

Building set of properties for class from text file using macros in haxe

I am trying to build a class during macro time from a file formated like this:

myString;String
myInt;Int
myCustomClass;CustomClass

Now, I am not adding the module to classes, so the macro has to resolve it.

This is my builder macro:

class Builder {
    macro public static function buildController(resourcePath:String):Array<Field> {
        resourcePath = haxe.macro.Context.resolvePath(resourcePath);
        var pos = haxe.macro.Context.currentPos();
        var fields = haxe.macro.Context.getBuildFields();

        var entries = sys.io.File.getContent(resourcePath).split("\n");

        for (e in entries) {
            var data = e.split(";");
            var varname = data[0];
            var classname = data[1];
            var packname = [];
            switch(haxe.macro.Context.getType(classname)) {
                case TInst(t,_): packname = t.get().pack;
                default: throw "Class not found";
            }
            fields.push( { name : varname
                         , doc : null
                         , meta : []
                         , access : [APrivate]
                         , kind : FVar(TPath( { pack : packname
                                              , name : classname
                                              , params : []
                                              , sub : null })
                                                  , null)
                         , pos : pos } );
        }
        return fields;
    }
}

And when I use it like this:

@:build(Builder.buildController("./data.txt"))
class Main {
  static public function main() {}
}

I get this error:

/usr/lib/haxe/std/haxe/macro/Context.hx:249: characters 37-45 : Invalid field access : __s Builder.hx:17: characters 19-56 : Called from Main.hx:2: characters 2-7 : Called from Aborted

How can I build properties in a macro from a text file like this?

Upvotes: 1

Views: 122

Answers (1)

xadm
xadm

Reputation: 8428

I'm not an expert but it looks like type resolving issues (custom class?). Check it separately, strings one by one instead of array/file (will work for String and Int, failing for custom). Trace out TPath results, it can be a issue like https://github.com/HaxeFoundation/haxe/issues/1542

Look at http://pastebin.com/fAwWPk8q

Upvotes: 1

Related Questions