Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala macros: how to read an annotation object

I want to do a similar thing as Scala Macros: Checking for a certain annotation My annotation looks like:

class extract(val name: String) extends StaticAnnotation

And I'm using it like this:

case class MainClass(@extract("strings") foo: String, bar: Int)

I'm trying to get foo parameter Symbol because it has an @extract annotation:

val extrList = params.map { param: Symbol =>
  param.annotations.collect {
    case extr if extr.tpe  <:< c.weakTypeOf[extract] =>
      val args = extr.scalaArgs
      if (args.size != 1)
        abort("@extract() should have exactly 1 parameter")
      getExtractValue(args.head) -> param
  }
}

The getExtractValue method looks like this:

def getExtractValue(tree: Tree): String = ???

How do I get the value name of the @extract annotation

Update

The Tree I get from scalaArgs seems too be unusable by c.eval()

param: Symbol =>
    param.annotations.collect {
      case ann if ann.tpe <:< c.weakTypeOf[extract] =>
        val args = ann.scalaArgs
        val arg0 = args.head
        val name: String = c.eval(c.Expr(arg0))
        echo(s"args @extract(name = $name)")
        name -> param
    }

Gives the error

[error] exception during macro expansion:
[error] scala.tools.reflect.ToolBoxError: reflective toolbox has failed: cannot
operate on trees that are already typed
[error]         at scala.tools.reflect.ToolBoxFactory$ToolBoxImpl$ToolBoxGlobal.
verify(ToolBoxFactory.scala:74)

the full stacktrace points to c.eval (I separated c.eval and c.Expr)

like image 585
Jaap Avatar asked Jan 03 '14 16:01

Jaap


1 Answers

In this case:

def getExtractValue(tree: Tree) = tree match {
  case Literal(Constant(str: String)) => str
}
like image 95
ghik Avatar answered Nov 14 '22 14:11

ghik