mercredi 6 mars 2019

How to use named arguments in Scala user defined annotations?

I the following code, I was able get the first annotation object "Publishable", but not the second. The 2nd one uses named arguments, which translated to x$2, x$3, x$1 as arguments in the AST. How do I do this properly?

class Publishable(
    val path: String = "",
    val format: String = "",
    val saveMode: String = "overwrite"
) extends scala.annotation.StaticAnnotation {
    def show: Unit = {
        println(s"path=$path, format=$format, saveMode=$saveMode")
    }
}

class TestObject {
    @Publishable("a", "b")
    def method1 = 100

    @Publishable(saveMode = "c")
    def method2 = 200
}

import scala.reflect.runtime.{universe => ru}
import ru._

val mirror = runtimeMirror(getClass.getClassLoader)
typeOf[TestObject].decls.foreach(field => {
    println(s"==== $field ====")
    field.annotations.foreach(anno => {
        println(s"tree = ${show(anno.tree)}")
        import scala.tools.reflect.ToolBox
        val tb = mirror.mkToolBox()
        val pub = tb.eval(tb.untypecheck(anno.tree)).asInstanceOf[Publishable]
        pub.show
    })
})

Output:

==== constructor TestObject ====
==== method method1 ====
tree = new Publishable("a", "b", $line41.$read.$iw.$iw.Publishable.<init>$default$3)
path=a, format=b, saveMode=overwrite
==== method method2 ====
tree = new Publishable(x$2, x$3, x$1)
java.lang.IllegalArgumentException: Could not find proxy for val x$2: String in List(value x$2, value <local TestObject>, class TestObject, object $iw, object $iw, object $read, package $line42, package <root>) (currentOwner= method wrapper )
at scala.tools.nsc.transform.LambdaLift$LambdaLifter.scala$tools$nsc$transform$LambdaLift$LambdaLifter$$searchIn$1(LambdaLift.scala:326)
at scala.tools.nsc.transform.LambdaLift$LambdaLifter.scala$tools$nsc$transform$LambdaLift$LambdaLifter$$searchIn$1(LambdaLift.scala:331)
....





Aucun commentaire:

Enregistrer un commentaire