3. C
Expand special directive in source code
before compilation by pre-processor
#define square(x) ((x) * (x))
printf("i * i = %dn", i, square(i));
#define DEBUG
#ifdef DEBUG
printf("debug: i = %dn", i)
#endif
5. Example in Scala
def assert(cond: Boolean, msg: String): Unit
= macro assertImpl
def assertImpl(c: Context)
(cond: c.Expr[Boolean], msg: c.Expr[String]) = {
import c.universe._
q"if(!$cond){ throw new AssertionError($msg) }"
}
6. Example in Scala
assert(i == 1, "i does not 1")
if(i == 1){
throw new AssertionError("i does not 1")
}
Expand by Macro
Note: Macro have to be compiled before main compilation
9. Quill
● Database access library for Scala
● Do in compile-time by macro
○ Translate typesafe DSL to SQL
○ SQL validation against real database
val q = quote {
query[Person].filter(p => p.age > 18)
}
// SELECT p.id, p.name, p.age FROM Person p WHERE p.age > 18
http://getquill.io/
11. Macro type
● def macro
○ callable as same as normal function
● Macro annotation
○ triggered by annotation
○ requires Macro Paradise plug-in
@main object Test {
println("hello world")
}
object Test {
def main(args: Array[String]): Unit = {
println("hello world")
}
}
Expand by Macro annotation
16. Future: scala.mata
● Metaprogramming toolkit for Scala
● Replace scala.reflect
○ More simple and safe
● Scala Macro will move to scala.meta based
○ Only Macro annotation is available by Macro
Paradise plug-in currently