9

The following macro, extracted from a larger example, is supposed to create a tree with nothing but a reference to this:

def echoThisImpl(c:Context): c.Expr[Any] = {
  import c.universe._

  val selfTree = This(c.enclosingClass.symbol)
  c.Expr[AnyRef](selfTree)
}

def echoThis: Any = macro CallMacro.echoThisImpl

But a call to echoThis such as

object Testing extends App {
  val thisValue = CallMacro.echoThis
  println(thisValue)
}

fails to compile, with the message

[error] /home/rafael/dev/scala/goose/goose-macros/src/test/scala/Testing.scala:8: type mismatch;
[error]  found   : <noprefix>
[error]  required: Any
[error]   val thisValue = CallMacro.echoThis

If I set the -Ymacro-debug-lite flag the generated tree is This(newTermName("<local Testing>")).

1 Answers1

10

There are two options of achieving what you want:

1) Use This(tpnme.EMPTY). Currently this doesn't compile, so you'll have to use This(newTypeName("")) instead, but in RC1 this will be fixed.

2) Use This(c.enclosingClass.symbol.asModule.moduleClass). Currently this doesn't work, because of https://issues.scala-lang.org/browse/SI-6394, but in RC1 this will be fixed.

Eugene Burmako
  • 13,028
  • 1
  • 46
  • 59
  • Thanks for responding Eugene. It wasn't quite enough to get me through. IIUC `c.prefix` is an expression for the tree that refers to the `object` where the macro is defined. – Rafael de F. Ferreira Sep 19 '12 at 02:46
  • (continuing) `This()` takes a symbol, and I believe I'm looking for the symbol referring to the enclosing class of the macro call. I want the call ` def echoThis: Any = macro MacroImpl.echoThis` to be the same as ` def echoThis: Any = this` – Rafael de F. Ferreira Sep 19 '12 at 02:53