Adding extra trait to object using scala macro annotation

孤人 提交于 2019-12-08 07:10:34

问题


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 {}

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

where bases holds the existing extensions in the form List of Ident(newTypeName("Bar"))

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.

Any help appreciated!


回答1:


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.



来源:https://stackoverflow.com/questions/21680630/adding-extra-trait-to-object-using-scala-macro-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!