Skip to content

Instantly share code, notes, and snippets.

@kmizu
Created December 13, 2019 05:52
Show Gist options
  • Save kmizu/abdca1cf612e7a10b68337deac0f63e6 to your computer and use it in GitHub Desktop.
Save kmizu/abdca1cf612e7a10b68337deac0f63e6 to your computer and use it in GitHub Desktop.
import scala.reflect.macros.whitebox.Context
import scala.language.experimental.macros
object Macros {
def test(body: Any*): Unit = macro testImpl
def testImpl(c: Context)(body: c.Expr[Any]*) : c.Expr[Unit] = {
import c.universe._
for(expr <- body) {
print("expr is ")
expr.tree match {
case Ident(term) =>
println(s"term ${term}")
case Literal(Constant(v:Int)) =>
println(s"integer literal ${v}")
case Literal(Constant(v:String)) =>
println(s"string literal ${v}")
}
}
c.Expr[Unit](Literal(Constant(())))
}
}
~/work/macros
[k.mizushima]$ scalac Usage.scala
expr is term while
expr is integer literal 1
expr is term $colon
expr is term print
expr is string literal hoge
import Macros._
object Usage {
def main(args: Array[String]): Unit = {
val `while`= 100
val `:` = 200
val `print` = "foo"
test(`while`, 1, `:`, `print`, "hoge")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment