与此类似:What's up with position on Scala macros?
我使用-Yrangepos
,宏天堂(2.1.0-M1)和scala(2.11.2)
当我使用注释宏时,树位置返回范围位置。问题是def宏如下面只返回偏移位置。
def macro_impl[T](c: Context)(code: c.Expr[T]): c.Expr[Unit] = {
println(code.tree.pos.start, code.tree.pos.end) // => start == end
c.Expr[Unit](q"()") // w/e
}
如何从code
树获得范围位置?
修改
我将问题缩减为以下项目https://github.com/MasseGuillaume/def-macros-pos-issue
// Build
scalacOptions ++= Seq("-Yrangepos", "-unchecked", "-deprecation", "-feature")
// Macros
import scala.language.experimental.macros
import scala.reflect.macros.Context
object Macros {
def impl[T](c: Context)(code: c.Expr[T]) = {
import c.universe._
implicit def liftq = Liftable[c.universe.Position] { p ⇒
q"(${p.point}, ${p.end})"
}
c.Expr[(Int, Int)](q"${code.tree.pos}")
}
def pos[T](code: T): (Int, Int) = macro impl[T]
}
我确实得到了一个范围,但它并不准确:
object Test extends App {
val pos = Macros.pos {
1
}
println(pos) // (55,56)
}
// that's
object Test extends App {
val pos = Macros.pos {
^^
1
}
println(pos)
}
// Expecting
object Test extends App {
val pos = Macros.pos {
^
1
}
^
println(pos)
}