1

I'm using macro annotation to instrument code. How can I get the range position of some expressions ?

@ScalaKata object SHA {
    val foo = "foo" 
    val bar = "bar"
    foo; bar
    // ...
}
// result: Map((75, 78) -> "foo", (80, 83) -> "bar")

The instrumenting macro:

package com.scalakata.eval

import scala.reflect.macros.blackbox.Context

import scala.language.experimental.macros
import scala.annotation.StaticAnnotation

object ScalaKataMacro {

  def impl(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
    import c.universe._


    val result: Tree = {
      val eval = newTermName("eval$")
      annottees.map(_.tree).toList match {
        case q"object $name { ..$body }" :: Nil => {

          val instr = newTermName("instr$")
          implicit def lift = Liftable[c.universe.Position] { p =>
            q"(${p.start}, ${p.end})"
          }
          def instrument(rhs: Tree): Tree = {
            q"""
            {
              val t = $rhs
              ${instr}(${rhs.pos}) = t
              t
            }
            """
          }

          val bodyI = body.map {
            case ident: Ident => instrument(ident)
            case otherwise => otherwise
          }
          q"""
          object $name { 
            val $instr = scala.collection.mutable.Map.empty[(Int, Int), Any]

            def $eval() = {
              ..$bodyI
              $instr
            }
          }
          """
        }
      }
    }
    c.Expr[Any](result)
  }
}

class ScalaKata extends StaticAnnotation {
  def macroTransform(annottees: Any*) = macro ScalaKataMacro.impl
}

I have range option enabled scalacOptions += "-Yrangepos"

I'm currently getting only the starting position: result: Map((75, 75) -> "foo", (80, 80) -> "bar")

4

1 回答 1

1

天堂中有一个错误会破坏宏参数的范围位置。它现在已在新发布的 2.1.0-SNAPSHOT 中修复。

然而,Scala 2.11.0 和 2.11.1 中也有一个回归,它也会破坏范围位置。因此,您将只能在 2.10.x 或即将发布的 2.11.2(计划于 7 月底)中访问宏注释中的范围位置。

于 2014-06-28T16:12:54.140 回答