How to print source condition code "IF" in "THEN"

I would like to print the source code for the Scala condition of the IF condition while in the THEN section.

Example: IF{ 2 + 2 < 5 } THEN { println("I am in THEN because: " + sourceCodeOfCondition) }

Let's skip the THEN section right now, the question is how to get the block source after IF?

I assume that IF should be a macro ...

Note: this question is an overridden version of Macro for accessing the source code of a function at runtime , where I described what { val i = 5; List(1, 2, 3); true }.logValueImplworks for me (according to another question Macro for accessing the text of source code at runtime ).

+3
source share
1 answer

, :

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) }")
  }
}

:

object Demo {
  import Conditional._

  val x = 1

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

:

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

, , , .

. .

+3

All Articles