[英]How to declare instantiation in Haxe macro function
I want to create a macro that generates this code for me: 我想创建一个为我生成此代码的宏:
if (myEntity.get(Attack) == null) myEntity.add(new Attack());
if (myEntity.get(Confused) == null) myEntity.add(new Confused());
if (myEntity.get(Defend) == null) myEntity.add(new Defend());
if (myEntity.get(Offense) == null) myEntity.add(new Offense());
In code I'd like to declare/use it like this: 在代码中我想声明/使用它像这样:
EntityMacroUtils.addComponents(myEntity, Attack, Confused, Defend, Offense);
The current macro function looks like this: 当前的宏函数如下所示:
macro public static function addComponents(entity:ExprOf<Entity>, components:Array<ExprOf<Class<Component>>>):Expr
{
var exprs:Array<Expr> = [];
for (componentClass in components)
{
var instance = macro $e { new $componentClass() }; // problem is here
var expr = macro if ($entity.get($componentClass) == null) $entity.add(instance);
exprs.push(expr);
}
return macro $b{ exprs };
}
This macro function is incorrect, I get the error: 这个宏函数不正确,我收到错误:
EntityMacroUtils.hx:17: characters 22-43 : Type not found : $componentClass
EntityMacroUtils.hx:17:字符22-43:未找到类型:$ componentClass
The problem is I don't know how to define new $componentClass()
. 问题是我不知道如何定义
new $componentClass()
。 How would I solve this? 我该如何解决这个问题?
I also want to avoid to have Type.createInstance
in the output code. 我还想避免在输出代码中使用
Type.createInstance
。
One way to programmatically generate instantiation code is by using "old school" enums AST building (compatible Haxe 3.0.1+): 以编程方式生成实例化代码的一种方法是使用“旧学校”枚举AST构建(兼容Haxe 3.0.1+):
// new pack.age.TheClass()
return {
expr:ENew({name:"TheClass", pack:["pack", "age"], params:[]}, []),
pos:Context.currentPos()
};
An improved syntax using reification is possible: 使用具体化的改进语法是可能的:
// new pack.age.TheClass()
var typePath = { name:"TheClass", pack:["pack", "age"], params:[] };
return macro new $typePath();
Now, for a convenient "instantiation helper" function syntax, we need to do some contorsions to extract a type path from the expression we receive in the macro function: 现在,为了方便的“实例化助手”函数语法,我们需要做一些扭曲来从我们在宏函数中接收的表达式中提取类型路径:
// new Foo(), new pack.Bar(), new pack.age.Baz()
instantiate(Foo, pack.Bar, pack.age.Baz);
macro static function instantiate(list:Array<Expr>)
{
var news = [for (what in list) {
var tp = makeTypePath(what);
macro new $tp();
}];
return macro $b{news};
}
#if macro
static function makeTypePath(of:Expr, ?path:Array<String>):TypePath
{
switch (of.expr)
{
case EConst(CIdent(name)):
if (path != null) {
path.unshift(name);
name = path.pop();
}
else path = [];
return { name:name, pack:path, params:[] };
case EField(e, field):
if (path == null) path = [field];
else path.unshift(field);
return makeTypePath(e, path);
default:
throw "nope";
}
}
#end
In case anyone is in need for answers, I got this Thanks to ousado on the Haxe IRC chat: 如果有人需要答案,我得到了这个感谢ousado在Haxe IRC聊天:
If you do it in macro alone you can do this: 如果你只在宏中执行它,你可以这样做:
var ct = macro : pack.age.SomeTypename;
var tp = switch ct { case TPath(tp):tp; case _: throw "nope"; }
var expr = macro new $tp();
..or, if you explicitly construct tp
: ..或者,如果你明确地构造
tp
:
var tp = {sub:'SomeTypeName',params:[],pack:['pack','age'],name:"SomeModuleName"}
As you can see, the complex type path is explicitly given here. 如您所见,此处明确给出了复杂类型路径。
Unfortunately, Haxe don't really have a concise syntax for types in expression positions. 不幸的是,Haxe对于表达式位置中的类型并没有真正简洁的语法。 You can pass
( _ : TypeName )
to provide an expression that contains a ComplexType. 您可以传递
( _ : TypeName )
以提供包含ComplexType的表达式。
But if you want to pass a type as argument, you could do it like this: 但是如果你想传递一个类型作为参数,你可以这样做:
import haxe.macro.Expr;
using haxe.macro.Tools;
class Thing {
public function new(){}
}
class OtherThing {
public function new(){}
}
class TMacroNew {
macro static function instances( arr:Array<Expr> ) {
var news = [for (e in arr) {
var ct = switch e.expr { case EParenthesis({expr:ECheckType(_,ct)}):ct; case _: throw "nope"; };
var tp = switch ct { case TPath(tp):tp; case _: throw "nope"; };
macro new $tp();
}];
trace( (macro $b{news}).toString());
return macro $b{news};
}
static function main(){
instances( (_:Thing), (_:Thing), (_:OtherThing) );
}
}
..if you want a list of types, you might want to go for a parameter list like ( _ : L< One,Two,Three> )
. ..如果你想要一个类型列表,你可能想要一个参数列表,如
( _ : L< One,Two,Three> )
。
The accepted answer is problematic because it breaks when type parameters are involved, or when support for non-nominal types should be included. 接受的答案是有问题的,因为当涉及类型参数时,或者当应包括对非标称类型的支持时,它会中断。
I updated the example using two alternatives for a more concise notation for the list of types, while still allowing syntax for actual types. 我使用两个替代方法更新了示例,以便为类型列表提供更简洁的表示法,同时仍允许实际类型的语法。
import haxe.macro.Expr;
using haxe.macro.Tools;
class Thing {
public function new(){}
}
class OtherThing {
public function new(){}
}
class TPThing<T>{
public function new(){}
}
class TMacroNew {
macro static function instances( e:Expr ) {
var tps = switch e.expr {
case EParenthesis({expr:ECheckType(_,TPath({params:tps}))}):tps;
case ENew({params:tps},_):tps;
case _: throw "not supported";
}
var type_paths = [ for (tp in tps) switch tp {
case TPType(TPath(tp)):tp;
case _: throw "not supported";
}];
var news = [for (tp in type_paths) macro new $tp()];
trace( (macro $b{news}).toString());
return macro $b{news};
}
static function main(){
instances( (_:L<Thing,Thing,OtherThing,TPThing<Int>> ) );
instances( new L<Thing,Thing,OtherThing,TPThing<Int>>() );
}
}
Edit: The L in L< ... >
could be any valid type name. 编辑:
L< ... >
中的L< ... >
可以是任何有效的类型名称。 Its only purpose is allowing to write a comma-separated list of types in valid syntax. 它的唯一目的是允许以有效语法编写以逗号分隔的类型列表。 Since macro functions take expressions as arguments, we have to use an expression that allows/requires a type, like:
( _ :T ), new T(), var v:T, function(_:T):T {}
. 由于宏函数将表达式作为参数,我们必须使用允许/需要类型的表达式,如:
( _ :T ), new T(), var v:T, function(_:T):T {}
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.