【问题标题】:Scala macros example not working on Scala 2.12.6Scala 宏示例不适用于 Scala 2.12.6
【发布时间】:2018-08-08 15:14:57
【问题描述】:

我从here获取以下代码。

package example.macros
import scala.language.experimental.macros
import scala.reflect.macros.Context
import scala.collection.mutable.{ListBuffer, Stack}

object Macros {
  def printf(format: String, params: Any*): Unit = macro printf_impl

  def printf_impl(c: Context)(format: c.Expr[String], params: c.Expr[Any]*): c.Expr[Unit] = {
    import c.universe._
    val Literal(Constant(s_format: String)) = format.tree

    val evals = ListBuffer[ValDef]()
    def precompute(value: Tree, tpe: Type): Ident = {
      val freshName = TermName(c.fresh("eval$"))
      evals += ValDef(Modifiers(), freshName, TypeTree(tpe), value)
      Ident(freshName)
    }

    val paramsStack = Stack[Tree]((params map (_.tree)): _*)
    val refs = s_format.split("(?<=%[\\w%])|(?=%[\\w%])") map {
      case "%d" => precompute(paramsStack.pop, typeOf[Int])
      case "%s" => precompute(paramsStack.pop, typeOf[String])
      case "%%" => Literal(Constant("%"))
      case part => Literal(Constant(part))
    }

    val stats = evals ++ refs.map(ref => reify(print(c.Expr[Any](ref).splice)).tree)
    c.Expr[Unit](Block(stats.toList, Literal(Constant(()))))
  }
}

或在 IDE 中查看:

当我尝试在 IntelliJ 中编译我的项目时,我得到了这个:

怎么了?我该如何解决?

【问题讨论】:

  • 显示你的build.sbt

标签: scala macros scala-macros


【解决方案1】:

我在使用 IntelliJ 时遇到了完全相同的问题。我通过声明对scala-reflect ("org.scala-lang" % "scala-reflect" % "2.12.6") 的依赖来解决它。

【讨论】:

    【解决方案2】:

    从 scala 2.11 开始,scala.reflect.macros.Context 上下文被拆分为 scala.reflect.macros.whitebox.Contextscala.reflect.macros.blackbox.Context

    你必须导入你想要的!

    更多解释在这里:https://docs.scala-lang.org/overviews/macros/blackbox-whitebox.html

    【讨论】:

    • 它们(cala.reflect.macros.whitebox.Context 和 scala.reflect.macros.blackbox.Context)仍然没有导入到我的 IDE 中。
    猜你喜欢
    • 2015-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-30
    • 1970-01-01
    • 2017-02-13
    • 2012-06-24
    • 2018-12-21
    相关资源
    最近更新 更多