1
votes

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

1 Answers

2
votes

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.