lundi 2 novembre 2015

Eval Tree in Scala 2.11.7

I'm trying to implement JSON-RPC server in Scala and want to mark my remote methods with annotations. Also it will be nice if method itself should not be worried about input parameters validation, so I want to put this validations inside annotation. I ended up with this:

class RPCMethod(validators: (String, PartialFunction[Any, Boolean])*) extends StaticAnnotation

And remote method is annotated like this:

@RPCMethod(
    "name" -> {
        case x: String => x == "Andrey"
    }
)

Now I'm trying to extract the {case ...} part and eval it to a function to check inbound value. But all I could get with reflection is a Tree:

val annotation = method.annotations.find(_.tree.tpe == typeOf[RPCMethod]).get
val validators = annotation.tree.children.tail
if (validators.isEmpty) {
    return true
} else {
    validators.head match {
        case q"scala.this.Predef.ArrowAssoc[$_](${name: String}).->[$_]($func)" => // Don't know how to eval 'func'
        case _ => throw some error
    }
}

So how can I get a valid function object from this Tree?





Aucun commentaire:

Enregistrer un commentaire