Artur Stanek
Artur Stanek

Reputation: 85

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

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

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

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

I assume that IF should be a macro...

Note: this question is redefined version of Macro to access source code of function at runtime where I described that { val i = 5; List(1, 2, 3); true }.logValueImpl works for me (according to other question Macro to access source code text at runtime).

Upvotes: 3

Views: 684

Answers (2)

Will Sargent
Will Sargent

Reputation: 4396

As of 2.13, you can also do this by wrapping the expression, which means you don't have to define a custom if function:

implicit def debugIf[A]: DebugIf => Unit = { cond: DebugIf =>
  logger.info(s"condition = {}, result = ${cond.result}", cond.code)
}

decorateIfs {
  if (System.currentTimeMillis() % 2 == 0) {
    println("decorateIfs: if block")
  } else {
    println("decorateIfs: else block")
  }
}

with the macro implementation:

  def decorateIfs[A: c.WeakTypeTag](a: c.Expr[A])(output: c.Expr[DebugIf => Unit]): c.Expr[A] = {
    def isEmpty(tree: Trees#Tree): Boolean = {
      tree match {
        case Literal(Constant(())) =>
          true
        case other =>
          false
      }
    }

    c.Expr[A] {
      a.tree match {
        // https://docs.scala-lang.org/overviews/quasiquotes/expression-details.html#if
        case q"if ($cond) $thenp else $elsep" =>
          val condSource = extractRange(cond) getOrElse ""
          val printThen = q"$output(DebugIf($condSource, true))"
          val elseThen = q"$output(DebugIf($condSource, false))"

          val thenTree = q"""{ $printThen; $thenp }"""
          val elseTree = if (isEmpty(elsep)) elsep else q"""{ $elseThen; $elsep }"""
          q"if ($cond) $thenTree else $elseTree"
        case other =>
          other
      }
    }
  }

  private def extractRange(t: Trees#Tree): Option[String] = {
    val pos = t.pos
    val source = pos.source.content
    if (pos.isRange) Option(new String(source.drop(pos.start).take(pos.end - pos.start))) else None
  }

  case class DebugIf(code: String, result: Boolean)

Upvotes: 0

Travis Brown
Travis Brown

Reputation: 139038

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.

Upvotes: 3

Related Questions