how to print variable name and value using a scala macro?

别来无恙 提交于 2019-12-22 05:19:25

问题


I am sure there is a more elegant way of writing the following macro which prints the name and value of a variable:

def mprintx(c: Context)(linecode: c.Expr[Any]): c.Expr[Unit] = {
    import c.universe._

    val namez = (c.enclosingImpl match {
        case ClassDef(mods, name, tparams, impl) =>
            c.universe.reify(c.literal(name.toString).splice)
        case ModuleDef(mods, name, impl) =>
            c.universe.reify(c.literal(name.toString).splice)
        case _ => c.abort(c.enclosingPosition, "NoEnclosingClass")
    }).toString match {
        case r_name(n) => n
        case _         => "Unknown?"
    }

    val msg = linecode.tree.productIterator.toList.last.toString.replaceAll("scala.*\\]", "").replaceAll(namez+"\\.this\\.", "").replaceAll("List", "")
    reify(myPrintDln(c.Expr[String](Literal(Constant(msg))).splice+" ---> "+linecode.splice))
}

def myPrintIt(linecode: Any) = macro mprintx

called by the following program:

object Zabi2 extends App {
val l = "zab"
val kol = 345
var zub = List("2", 89)
val zubi = List(zub,l,kol)

printIt(l)
printIt(l, kol, (l, zub),zubi)
}

which prints:

l ---> zab
(l, kol, (l, zub), zubi) ---> (zab,345,(zab,List(2, 89)),List(List(2, 89), zab, 345))

Thanks in advance for your help.

来源:https://stackoverflow.com/questions/21857130/how-to-print-variable-name-and-value-using-a-scala-macro

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!