问题描述
我在Scala的2.10.3使用宏天堂.我在那里我想一个特征添加到对象宏注释,e.g:
I'm on Scala 2.10.3 using Macro Paradise. I have a macro annotation where I'm trying to add a trait to on object, e.g:
@MyAnnotation
object Foo extends Bar {}
扩展后,我想要类似的东西
After expansion I want something like:
object Foo extends Bar with Baz {}
Baz
是在编译范围内可访问的特征.使用微距天堂,我可以清晰地解构我的目标树:
Where Baz
is a trait accessible in the compilation scope. Using macro paradise I can cleanly destructure my target tree:
q"object $obj extends ..$bases { ..$body }" = tree
其中碱持有订货号(newTypeName(酒吧"))
where bases holds the existing extensions in the form List of Ident(newTypeName("Bar"))
我可以在基础上添加一个额外的Baz
条目并重建树,问题是目标可能已经"包含了Baz
.在这种情况下,我不想添加它.给我的项名称缩短.有没有一种方法可以将它们转换为宏内的实际类型引用?
I could just add an extra Baz
entry to bases and reconstruct the tree, the problem is the target might "already" contain Baz
. In this case I don't want to add it. The term names given to me are shortened. Is there a way of converting them to actual type references inside the macro?
我试过在宏以下内容:,但我得到了以下错误:
I've tried the following in the macro: c.typeCheck(Ident(newTypeName("Baz")))
but I get the following error:
scala.reflect.macros.TypeCheckException: trait some.Baz is not a value
我已经通过的背景下审视,看看那里有其他任何明显的方法来使用,但没有跳出.
I've looked through context to see if theres any other obvious methods to use, but none jumps out.
任何帮助表示赞赏!
推荐答案
在斯卡拉2.10,c.typeCheck总是将它的参数作为一个术语,你需要去加倍努力,以类型检查,表示类型的树.
In Scala 2.10, c.typeCheck always treats its argument as a term, and you need to go the extra mile to typecheck a tree representing a type.
此答案说明了一种将类型作为类型进行类型检查的解决方法,并概述了特定于宏注释的限制:.
This answer explains a workaround to typecheck something as a type and outlines a limitation specific to macro annotations: Can't access Parent's Members while dealing with Macro Annotations.
这篇关于使用Scala宏注释为对象添加额外特征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!