How to print source code of “IF” condition in “THEN”

跟風遠走 提交于 2019-12-06 02:53:04
Travis Brown

Off-the-cuff implementation since I only have a minute:

import scala.reflect.macros.Context
import scala.language.experimental.macros

case class Conditional(conditionCode: String, value: Boolean) {
  def THEN(doIt: Unit) = macro Conditional.THEN_impl
}

object Conditional {
  def sourceCodeOfCondition: String = ???

  def IF(condition: Boolean) = macro IF_impl

  def IF_impl(c: Context)(condition: c.Expr[Boolean]): c.Expr[Conditional] = {
    import c.universe._

    c.Expr(q"Conditional(${ show(condition.tree) }, $condition)")
  }

  def THEN_impl(c: Context)(doIt: c.Expr[Unit]): c.Expr[Unit] = {
    import c.universe._

    val rewriter = new Transformer {
      override def transform(tree: Tree) = tree match {
        case Select(_, TermName("sourceCodeOfCondition")) =>
          c.typeCheck(q"${ c.prefix.tree }.conditionCode")
        case other => super.transform(other)
      }
    }

    c.Expr(q"if (${ c.prefix.tree }.value) ${ rewriter.transform(doIt.tree) }")
  }
}

And then:

object Demo {
  import Conditional._

  val x = 1

  def demo = IF { x + 5 < 10 } THEN { println(sourceCodeOfCondition) }
}

And finally:

scala> Demo.demo
Demo.this.x.+(5).<(10)

It's a desugared representation of the source, but off the top of my head I think that's the best you're going to get.

See my blog post here for some discussion of the technique.

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