如何打印"IF"源代码? "THEN"中的条件 [英] How to print source code of "IF" condition in "THEN"

查看:95
本文介绍了如何打印"IF"源代码? "THEN"中的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在THEN部分中打印IF条件的Scala源代码.

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

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

现在让我们跳过THEN部分,问题是:如何在IF之后获取块的源代码?

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

我认为IF应该是一个宏...

I assume that IF should be a macro...

注意:此问题是重新定义的宏版本运行时功能的源代码,其中我描述了{ val i = 5; List(1, 2, 3); true }.logValueImpl对我有用(根据其他问题

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).

推荐答案

即兴实施,因为我只有一分钟的时间:

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

然后:

object Demo {
  import Conditional._

  val x = 1

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

最后:

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.

这篇关于如何打印"IF"源代码? "THEN"中的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆