是的,这是可能的。
李浩一的宏Text
来自sourcecode
def text[T: c.WeakTypeTag](c: Compat.Context)(v: c.Expr[T]): c.Expr[sourcecode.Text[T]] = {
import c.universe._
val fileContent = new String(v.tree.pos.source.content)
val start = v.tree.collect {
case treeVal => treeVal.pos match {
case NoPosition ⇒ Int.MaxValue
case p ⇒ p.startOrPoint
}
}.min
val g = c.asInstanceOf[reflect.macros.runtime.Context].global
val parser = g.newUnitParser(fileContent.drop(start))
parser.expr()
val end = parser.in.lastOffset
val txt = fileContent.slice(start, start + end)
val tree = q"""${c.prefix}(${v.tree}, $txt)"""
c.Expr[sourcecode.Text[T]](tree)
}
这个几乎可以满足你的需求:
def convert[A](fn: => Text[A]): String = fn.source
convert(10 + 20 +
30
)
不幸的是,如果您在{}
块中有多条语句,sourcecode.Text
将仅捕获返回的最后一个表达式的源代码。
因为{ object I extends Seq {} }
实际上是{ object I extends Seq {}; () }
,所以这种宏在此情况下将不起作用。
因此,让我们编写自己的简单宏。
import scala.language.experimental.macros
import scala.reflect.macros.blackbox
def convert(fn: => Any): String = macro convertImpl
def convertImpl(c: blackbox.Context)(fn: c.Tree): c.Tree = {
import c.universe._
val pos = fn.pos
val res = new String(pos.source.content).slice(pos.start, pos.end)
Literal(Constant(res))
}
用法:
trait Seq
convert {
val i: Int = 1
object I extends Seq {}
10 + 20 + 30
convert(1)
}
请注意,在 def 宏扩展之前,宏的参数将进行类型检查(因此convert { val i: Int = "a" }
、convert { object I extends XXX }
(其中未定义XXX
)、convert { (; }
等都不会编译通过)。