1

In the following code, I was able get the first annotation object "Publishable", but not the second. The 2nd one used 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)
....
muon
  • 41
  • 5

1 Answers1

3

Compilation of your code produces a warning:

Warning: Usage of named or default arguments transformed this annotation
constructor call into a block. The corresponding AnnotationInfo
will contain references to local values and default getters instead
of the actual argument trees
  @Publishable(saveMode = "c")

You can work with default parameters like in

tree = new Publishable("a", "b", $line41.$read.$iw.$iw.Publishable.<init>$default$3)

using this technique: How do I access default parameter values via Scala reflection? for methods named like $lessinit$greater$default$3.

But regarding named parameters like in

tree = new Publishable(x$2, x$3, x$1)

their values are stored in local variables (the error says Could not find proxy for val x$2) and local variables can't be obtained via reflection (neither Scala reflection nor Java reflection) https://www.thecodingforums.com/threads/java-reflection-with-local-variables.599017/

You can work with default and named parameters of macro annotation at compile time: Getting Parameters from Scala Macro Annotation

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66