Adding extra trait to object using scala macro ann

2019-06-07 06:38发布

问题:

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.