Splicing together symbols with Scala macros

喜你入骨 提交于 2019-12-08 00:19:41

问题


I am trying to call a specialized collections library like FastUtil or Trove from generic Scala code. I would like to implement something like

def openHashMap[@specialized K, @specialized V]: ${K}2${V}OpenHashMap = 
   new ${K}2${V}OpenHashMap()

Where the ${X} is clearly not valid Scala, but just my meta notation for text substitution, so that openHashMap[Long, Double] would return a Long2DoubleOpenHashMap the type would be known at compile time. Is this possible with Scala macros. If so, which flavour? I know there are def macros, implicit macros, fundep materialization, macro annotations, type macros (now discontinued) ... and I think these are different in plain Scala-2.10, 2.10 macro paradise and Scala-2.11. Which, if any, of these are appropriate for this?

Or is there something else that can do this like byte code manipulation, language virtualization, ...? However, I do not believe the alternative I just mentioned can.


回答1:


Stealing the idea to use quasiquotes from this answer, we first add the macro-paradise plugin:

// build.sbt
scalaVersion := "2.10.2"

resolvers += Resolver.sonatypeRepo("snapshots")

addCompilerPlugin("org.scala-lang.plugins" % "macro-paradise" % "2.0.0-SNAPSHOT" 
  cross CrossVersion.full)

Then the macro looks like this:

// src/main/scala/Foo.scala
import reflect.macros.Context
import language.experimental.macros

trait Foo[A]
class IntFoo() extends Foo[Int]
class AnyFoo() extends Foo[Any]

object Foo {
  def apply[A]: Foo[A] = macro applyImpl[A]

  def applyImpl[A](c: Context)(t: c.WeakTypeTag[A]): c.Expr[Foo[A]] = {
    import c.universe._
    val aTpe    = t.tpe
    val prefix  = if (aTpe =:= typeOf[Int]) "Int" else "Any"
    val clazz   = newTypeName(s"${prefix}Foo")
    c.Expr(q"new $clazz()")
  }
}

And the test case:

// src/test/scala/Test.scala
object Test extends App {
  val fooInt = Foo[Int]
  val fooAny = Foo[Any]

  println(fooInt)
  println(fooAny)
}

Without the macro-paradise-plugin, you would need to construct the tree by hand, like New(clazz, ???), I couldn't get that to work so gave up, but it certainly would be possible, too.



来源:https://stackoverflow.com/questions/19076321/splicing-together-symbols-with-scala-macros

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