Haxe: access class <T> for Context.getLocalClass () in assembly macro
I want to make a macro that adds a field to my classes, and the field value should be the class of the class in which they are sitting. Here is my minimal example and it does not compile with the src / Base.hx error: 3: characters 2-11: Unknown identifier: foo.Foo
But if I transfer Foo from the foo package to the 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
{
}
+4
1 answer
EConst(CIdent("foo.Bar")) , , . . EField({ expr: EConst(CIdent("foo")) }, "Bar"), , foo.Bar ( trace ).
,
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);
}
}
EConst(CIdent) EField , , .
+4