Obtaining a WeakTypeTag for a given type in a Scala macro annotation

为君一笑 提交于 2019-12-12 03:25:33

问题


I'm writing a Scala macro annotation @model used to annotate my case classes and which automatically adds some metadata to the companion object of the annotated class, based on the fields of the annotated case class.

I would like to obtain more information about the type of the case class's parameters, especially, check if they implement a certain trait. I thought obtaining a WeakTypeTag for them was the way to go, but I can't seem to get one the way they are obtained in def macros.

Concretely: I want to be able to tell in this case, from the macro implementation of @model, that the address field of the User class has a type which extends ModelObject, and that date doesn't. Can I do that?

trait ModelObject
@model case case Address(street: String, city: String) extends ModelObject
@model case class User(name: String, since: Date, address: Address) extends ModelObject

回答1:


Trees that go into macro annotation arguments are purposefully untyped. However running c.typeCheck(q"(??? : <tree that represents the parent>)").tpe will provide the missing information. Don't forget to duplicate that tree before typechecking, because c.typeCheck mutates the tree in place, which might be undesireable.

There are limitations to what c.typeCheck can do. For some examples of that, see Can't access Parent's Members while dealing with Macro Annotations.



来源:https://stackoverflow.com/questions/27965857/obtaining-a-weaktypetag-for-a-given-type-in-a-scala-macro-annotation

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