我正在使用scalameta,我想要一个通用的测量注释,它会发送测量方法执行时间的测量值。
我使用了Qing Wei的缓存注释演示。 https://www.cakesolutions.net/teamblogs/scalameta-tut-cache
它适用于非异步方法,但由于ExecutionContext参数列表,我的属性与返回Future的方法不匹配。
我的注释看起来像这样:
package measurements
import scala.concurrent.Future
import scala.meta._
class measure(name: String) extends scala.annotation.StaticAnnotation {
inline def apply(defn: Any): Any = meta {
defn match {
case defn: Defn.Def => {
this match {
case q"new $_($backendParam)" =>
val body: Term = MeasureMacroImpl.expand(backendParam, defn)
defn.copy(body = body)
case x =>
abort(s"Unrecognized pattern $x")
}
}
case _ =>
abort("This annotation only works on `def`")
}
}
}
object MeasureMacroImpl {
def expand(nameExpr: Term.Arg, annotatedDef: Defn.Def): Term = {
val name: Term.Name = Term.Name(nameExpr.syntax)
annotatedDef match {
case q"..$_ def $methodName[..$tps](..$nonCurriedParams): $rtType = $expr" => {
rtType match {
case f: Future[Any] => q"""
val name = $name
println("before " + name)
val future: ${rtType} = ${expr}
future.map(result => {
println("after " + name)
result
})
"""
case _ => q"""
val name = $name
println("before " + name)
val result: ${rtType} = ${expr}
println("after " + name)
result
"""
}
}
case _ => abort("This annotation only works on `def`")
}
}
}
我使用这样的注释:
@measure("A")
def test(x: String): String = x
@measure("B")
def testMultipleArg(x: Int, y: Int): Int = x + y
我想将它用于这样的异步方法:
@measure("C")
def testAsync(x: String)(implicit ec: ExecutionContext) : Future[String] = {
Future(test(x))
}
但是我收到以下错误:
exception during macro expansion:
scala.meta.internal.inline.AbortException: This annotation only works on `def`
我认为问题是MeasureMacroImpl匹配,但我不确定如何匹配多个参数组。你们能帮助我吗?任何想法或示例代码将不胜感激。如果我问一个微不足道的问题,我对scala和scala meta很新,所以道歉。
答案 0 :(得分:2)
由于MeasureMacroImpl
与咖喱参数不匹配,您收到错误。
匹配curried params非常简单,只需使用
即可 scala
case q"..$_ def $methodName[..$tps](...$nonCurriedParams): $rtType = $expr"
请注意...$nonCurriedParams
而不是..$nonCurriedParams