Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I refer to enclosing "this" in a Scala macro?

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>")).

like image 729
Rafael de F. Ferreira Avatar asked Sep 18 '12 01:09

Rafael de F. Ferreira


1 Answers

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.

like image 168
Eugene Burmako Avatar answered Oct 05 '22 13:10

Eugene Burmako