2

Inside a macro is there a way of using the current Context to fully expand a type name? Eg something like:

context.resolveShortTypeNameToFullTypeName("Foo") = "com.acme.Foo"
senia
  • 37,745
  • 4
  • 88
  • 129
user3293336
  • 121
  • 1

1 Answers1

2

Your macro might expand in a tree that includes an arbitrary import prefix.Foo, so you're asking if you can query that enclosing tree: If I emit a name Foo, how would you typecheck it?

symbol.fullName is your answer.

val t = c.typeCheck(q"??? : Foo").tpe.typeSymbol.fullName

or use c.typecheck in 2.11.

or, if you can't find the scaladoc...

val k = c.asInstanceOf[scala.reflect.macros.contexts.Context]
locally {
  import k.universe._
  val n = k.callsiteTyper.typed(q"??? : Foo").tpe.typeSymbol.fullName
  println(n)
}

Where is Travis Brown Eugene Burmakro [sic] when you need him?

som-snytt
  • 39,429
  • 2
  • 47
  • 129
  • Yes, indeed it is possible to typecheck trees in macro expansions. There's even a special method for that in the public API called c.typeCheck, so there's no need to cast. In Scala 2.10, typeCheck can only work with terms and requires a small workaround to typecheck a type: http://stackoverflow.com/questions/21680630/adding-extra-trait-to-object-using-scala-macro-annotation/21682269. In Scala 2.11, typechecking will have a dedicated mode for types. – Eugene Burmako Feb 10 '14 at 20:02
  • @EugeneBurmako Thanks! I tried c.typecheck first and must have done something wrong. – som-snytt Feb 10 '14 at 20:50
  • 2
    Sorry—have a one-answer-max rule for my lunch breaks, and I'd [already spent mine](http://stackoverflow.com/a/21684752/334519) for today. – Travis Brown Feb 10 '14 at 21:37
  • @som-snytt. We've slightly changed the name in 2.11 - now it's c.typecheck, not c.typeCheck like in Scala 2.10. – Eugene Burmako Feb 11 '14 at 06:42