我的目标是javascript__。
我有一个运行在Context.onGenerate()上的宏,它将完全限定类型名称的子集保存到文件中。然后,另一个构建宏(将在下一个buid上运行)从文件中读取类型名称列表,以便创建一个静态字段到一个类中,该类应该在数组中保存这些类型(构造函数)。
我想从第二个宏生成的字段如下所示:
public static _entities:Array<Class<entities.Entity>> = [
entities.Foo,
entities.Bar,
...
];,它将生成以下javascript
MyClass._entities = [ entities_Foo, entities_Bar, ... ];现在,我试着手动编写字段,以确保所有内容都生成正确--确实如此。但是,我无法找到正确的方法来编写宏,因此我不得不添加一个标识符常量作为数组表达式的值,该表达式总是以“未知标识符”错误告终:
var id = { expr: EConst( CIdent( "entities.Foo" ) ),
pos: Context.currentPos() };
var ex = EArrayDecl([ id ]);
fields.push( {
name : "_entities",
access : [Access.APublic, Access.AStatic ],
pos : Context.currentPos(),
kind : FVar(
macro:Array<Class<entities.Entity>>,
// I've tried writing it without reification: (see above vars)
{ expr: ex, pos:Context.currentPos() }
// Or w/ reification:
macro $a{[ $i{ "entities.Foo" } ]}
)
});我试图用宏实现的目标可能吗?如果是这样的话,能指导我完成这个任务吗?
谢谢。
发布于 2017-03-21 19:01:38
问题是,您试图将其输出为单个标识符,而实际上它是一个点路径,应该将其表示为EField到第一个EIdent的链。幸运的是,Haxe有一个方便的"path“物化:试试$p{path.split(".")} ( path是您的"entities.Foo"字符串)。
发布于 2017-03-21 18:52:33
在深入了解API引用之后,我想出了如何做到这一点。事实证明,我需要的是TypedExpr,而不是一个标识符常量。
TTypeExpr和ModuleType of TClassDecl将得到正确的结果。所以我上面的示例代码变成:
static function getTypeRef( name:String ):Ref<ClassType>
{
var type = Context.getType( name );
switch( type )
{
default: return Context.error( "Expected a ClassType", Context.currentPos() );
case TInst( cr, _ ):
return cr;
}
}
static function getTypes()
{
// Obtain ClassType by identifier
var fooCls = getTypeRef( "entities.Foo" );
// Get a TypedExpr for the ClassType
var typedExpr:TypedExpr = {
expr : TTypeExpr( TClassDecl( fooCls ) ),
t : TInst( fooCls, [] ),
pos : Context.currentPos()
};
// Convert to Expr
var expr:Expr = Context.getTypedExpr( typedExpr );
var fields = Context.getBuildFields();
fields.push( {
name : "_entities",
access : [Access.APublic, Access.AStatic ],
pos : Context.currentPos(),
kind : FVar(
macro:Array<Class<entities.Entity>>,
macro $a{[ ${expr} ]} // <- Now it works here
)
});
return fields;
}https://stackoverflow.com/questions/42935006
复制相似问题