Skip to content

Instantly share code, notes, and snippets.

@kmizu
Created December 12, 2019 16:47
Show Gist options
  • Save kmizu/8db670f305a5a813860d49613c55e974 to your computer and use it in GitHub Desktop.
Save kmizu/8db670f305a5a813860d49613c55e974 to your computer and use it in GitHub Desktop.
A macro the reverse identifier
import scala.reflect.macros.whitebox.Context
import scala.language.experimental.macros
object Macros {
def reverse(id: Any): Any = macro reverseImpl
def reverseImpl(c: Context)(id: c.Expr[Any]) : c.Expr[Any] = {
import c.universe._
val Ident(TermName(name)) = id.tree
c.Expr[Any](Ident(TermName(name.reverse)))
}
}
~/work
[mizushima]$ scalac Macros.scala
~/work
[mizushima]$ scalac Usage.scala
~/work
[mizushima]$ scala Usage
200
object Usage {
def main(args: Array[String]): Unit = {
val foo = 100
val oof = 200
println(Macros.reverse(foo)) // oofを参照するので、「実行結果」は200になるはず
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment