Scala Macros - 元编程 Metaprogramming with Def Macros

    Scala Macros对scala函数库编程人员来讲是一项不可或缺的编程工具,能够经过它来解决一些用普通编程或者类层次编程(type level programming)都没法解决的问题,这是由于Scala Macros能够直接对程序进行修改。Scala Macros的工做原理是在程序编译时按照编程人员的意旨对一段程序进行修改产生出一段新的程序。具体过程是:当编译器在对程序进行类型验证(typecheck)时若是发现Macro标记就会将这个Macro的功能实现程序(implementation):一个语法树(AST, Abstract Syntax Tree)结构拉过来在Macro的位置进行替代,而后从这个AST开始继续进行类型验证过程。java

下面咱们先用个简单的例子来示范分析一下Def Macros的基本原理和使用方法:编程

1 object modules { 2    greeting("john") 3  } 4  
5  object mmacros { 6    def greeting(person: String): Unit = macro greetingMacro 7    def greetingMacro(c: Context)(person: c.Expr[String]): c.Expr[Unit] = ... 8  }

以上是Def Macros的标准实现模式。基本原理是这样的:当编译器在编译modules遇到方法调用greeting("john")时会进行函数符号解析、在mmacros里发现greeting是个macro,它的具体实如今greetingMacro函数里,此时编译器会运行greetingMacro函数并将运算结果-一个AST调用替表明达式greeting("john")。注意编译器在运算greetingMacro时会以AST方式将参数person传入。因为在编译modules对象时须要运算greetingMacro函数,因此greetingMacro函数乃至整个mmacros对象必须是已编译状态,这就意味着modules和mmacros必须分别在不一样的源代码文件里,并且还要确保在编译modules前先完成对mmacros的编译,咱们能够从sbt设置文件build.sbt看到它们的关系:api

 1 name := "learn-macro"
 2 
 3 version := "1.0.1"
 4 
 5 val commonSettings = Seq(  6   scalaVersion := "2.11.8",  7   scalacOptions ++= Seq("-deprecation", "-feature"),  8   libraryDependencies ++= Seq(  9     "org.scala-lang" % "scala-reflect" % scalaVersion.value, 10     "org.scala-lang.modules" %% "scala-parser-combinators" % "1.0.1", 11     "org.specs2" %% "specs2" % "2.3.12" % "test", 12     "org.scalatest" % "scalatest_2.11" % "2.2.1" % "test"
13  ), 14   addCompilerPlugin("org.scalamacros" % "paradise" % "2.1.0" cross CrossVersion.full) 15 ) 16 
17 lazy val root = (project in file(".")).aggregate(macros, demos) 18 
19 lazy val macros = project.in(file("macros")).settings(commonSettings : _*) 20 
21 lazy val demos  = project.in(file("demos")).settings(commonSettings : _*).dependsOn(macros)

注意最后一行:demos dependsOn(macros),由于咱们会把全部macros定义文件放在macros目录下。app

下面咱们来看看macro的具体实现方法:ide

 1 import scala.language.experimental.macros  2 import scala.reflect.macros.blackbox.Context  3 import java.util.Date  4 object LibraryMacros {  5   def greeting(person: String): Unit = macro greetingMacro  6 
 7   def greetingMacro(c: Context)(person: c.Expr[String]): c.Expr[Unit] = {  8  import c.universe._  9     println("compiling greeting ...") 10     val now = reify {new Date().toString} 11  reify { 12       println("Hello " + person.splice + ", the time is: " + new Date().toString) 13  } 14  } 15 }

以上是macro greeting的具体声明和实现。代码放在macros目录下的MacrosLibrary.scala里。首先必须import macros和Context。函数

macro调用在demo目录下的HelloMacro.scala里:工具

1 object HelloMacro extends App { 2  import LibraryMacros._ 3   greeting("john") 4 }

注意在编译HelloMacro.scala时产生的输出:测试

Mac-Pro:learn-macro tiger-macpro$ sbt [info] Loading global plugins from /Users/tiger-macpro/.sbt/0.13/plugins [info] Loading project definition from /Users/tiger-macpro/Scala/IntelliJ/learn-macro/project [info] Set current project to learn-macro (in build file:/Users/tiger-macpro/Scala/IntelliJ/learn-macro/) > project demos [info] Set current project to demos (in build file:/Users/tiger-macpro/Scala/IntelliJ/learn-macro/) > compile [info] Compiling 1 Scala source to /Users/tiger-macpro/Scala/IntelliJ/learn-macro/macros/target/scala-2.11/classes... [info] 'compiler-interface' not yet compiled for Scala 2.11.8. Compiling... [info] Compilation completed in 7.876 s [info] Compiling 1 Scala source to /Users/tiger-macpro/Scala/IntelliJ/learn-macro/demos/target/scala-2.11/classes... compiling greeting ... [success] Total time: 10 s, completed 2016-11-9 9:28:24
> 

从compiling greeting ...这条提示咱们能够得出在编译demo目录下源代码文件的过程当中应该运算了greetingMacro函数。测试运行后产生结果:ui

Hello john, the time is: Wed Nov 09 09:32:04 HKT 2016 Process finished with exit code 0

运算greeting其实是调用了greetingMacro中的macro实现代码。上面这个例子使用了最基础的Scala Macro编程模式。注意这个例子里函数greetingMacro的参数c: Context和在函数内部代码中reify,splice的调用:因为Context是个动态函数接口,每一个实例都有所不一样。对于大型的macro实现函数,可能会调用到其它一样会使用到Context的辅助函数(helper function),容易出现Context实例不匹配问题。另外reify和splice能够说是最原始的AST操做函数。咱们在下面这个例子里使用了最新的模式和方法:this

 1   def tell(person: String): Unit = macro MacrosImpls.tellMacro  2   class MacrosImpls(val c: Context) {  3  import c.universe._  4       def tellMacro(person: c.Tree): c.Tree = {  5       println("compiling tell ...")  6       val now = new Date().toString  7       q"""  8           println("Hello "+$person+", it is: "+$now)  9         """ 10  } 11   }

在这个例子里咱们把macro实现函数放入一个以Context为参数的class。咱们能够把全部使用Context的函数都摆在这个class里面你们共用统一的Context实例。quasiquotes是最新的AST操做函数集,能够更方便灵活地控制AST的产生、表达式还原等。这个tell macro的调用仍是同样的:

1 object HelloMacro extends App { 2  import LibraryMacros._ 3   greeting("john") 4   tell("mary") 5 }

测试运算产生下面的结果:

Hello john, the time is: Wed Nov 09 11:42:21 HKT 2016 Hello mary, it is: Wed Nov 09 11:42:20 HKT 2016 Process finished with exit code 0

Def Macros的Macro实现函数能够是泛型函数,支持类参数。在下面的例子咱们示范如何用Def Macros来实现通用的case class与Map类型的转换。假设咱们有个转换器CaseClassMapConverter[C],那么C类型能够是任何case class,因此这个转换器是泛型的,那么macro实现函数也就必须是泛型的了。大致来讲,咱们但愿实现如下功能:把任何case class转成Map:

 1  def ccToMap[C: CaseClassMapConverter](c: C): Map[String,Any] =
 2  implicitly[CaseClassMapConverter[C]].toMap(c)  3 
 4   case class Person(name: String, age: Int)  5   case class Car(make: String, year: Int, manu: String)  6 
 7   val civic = Car("Civic",2016,"Honda")  8   println(ccToMap[Person](Person("john",18)))  9  println(ccToMap[Car](civic)) 10 
11 ... 12 Map(name -> john, age -> 18) 13 Map(make -> Civic, year -> 2016, manu -> Honda)

反向把Map转成case class:

 1   def mapTocc[C: CaseClassMapConverter](m: Map[String,Any]) =
 2  implicitly[CaseClassMapConverter[C]].fromMap(m)  3 
 4   val mapJohn = ccToMap[Person](Person("john",18))  5   val mapCivic = ccToMap[Car](civic)  6  println(mapTocc[Person](mapJohn))  7  println(mapTocc[Car](mapCivic))  8 
 9 ... 10 Person(john,18) 11 Car(Civic,2016,Honda)

咱们来看看这个Macro的实现函数:macros/CaseClassConverter.scala

 1 import scala.language.experimental.macros  2 import scala.reflect.macros.whitebox.Context  3 
 4 trait CaseClassMapConverter[C] {  5  def toMap(c: C): Map[String,Any]  6  def fromMap(m: Map[String,Any]): C  7 }  8 object CaseClassMapConverter {  9   implicit def Materializer[C]: CaseClassMapConverter[C] = macro converterMacro[C] 10   def converterMacro[C: c.WeakTypeTag](c: Context): c.Tree = { 11  import c.universe._ 12 
13     val tpe = weakTypeOf[C] 14     val fields = tpe.decls.collectFirst { 15       case m: MethodSymbol if m.isPrimaryConstructor => m 16     }.get.paramLists.head 17 
18     val companion = tpe.typeSymbol.companion 19     val (toParams,fromParams) = fields.map { field =>
20     val name = field.name.toTermName 21     val decoded = name.decodedName.toString 22     val rtype = tpe.decl(name).typeSignature 23 
24       (q"$decoded -> t.$name", q"map($decoded).asInstanceOf[$rtype]") 25 
26  }.unzip 27 
28     q""" 29        new CaseClassMapConverter[$tpe] { 30         def toMap(t: $tpe): Map[String,Any] = Map(..$toParams) 31         def fromMap(map: Map[String,Any]): $tpe = $companion(..$fromParams) 32  } 33       """ 34  } 35 }

首先,trait CaseClassMapConverter[C]是个typeclass,表明了C类型数据的行为函数toMap和fromMap。咱们同时能够看到Macro定义implicit def Materializer[C]是隐式的,并且是泛型的,运算结果类型是CaseClassMapConverter[C]。从这个能够推断出这个Macro定义经过Macro实现函数能够产生CaseClassMapConverter[C]实例,C能够是任何case class类型。在函数ccToMap和mapTocc函数须要的隐式参数CaseClassMapConverter[C]实例就是由这个Macro实现函数提供的。注意咱们只能用WeakTypeTag来获取类型参数C的信息。在使用quasiquotes时咱们通常是在q括号中放入原始代码。在q括号内调用AST变量用$前缀(称为unquote)。对类型tpe的操做能够参考scala.reflect api。示范调用代码在demo目录下的ConverterDemo.scala里:

 1 import CaseClassMapConverter._  2 object ConvertDemo extends App {  3 
 4   def ccToMap[C: CaseClassMapConverter](c: C): Map[String,Any] =
 5  implicitly[CaseClassMapConverter[C]].toMap(c)  6 
 7   case class Person(name: String, age: Int)  8   case class Car(make: String, year: Int, manu: String)  9 
10   val civic = Car("Civic",2016,"Honda") 11   //println(ccToMap[Person](Person("john",18))) 12   //println(ccToMap[Car](civic))
13 
14   def mapTocc[C: CaseClassMapConverter](m: Map[String,Any]) =
15  implicitly[CaseClassMapConverter[C]].fromMap(m) 16 
17   val mapJohn = ccToMap[Person](Person("john",18)) 18   val mapCivic = ccToMap[Car](civic) 19  println(mapTocc[Person](mapJohn)) 20  println(mapTocc[Car](mapCivic)) 21   
22 }

在上面这个implicit Macros例子里引用了一些quasiquote语句(q"xxx")。quasiquote是Scala Macros的一个重要部分,主要替代了原来reflect api中的reify功能,具有更强大、方便灵活的处理AST功能。Scala Def Macros还提供了Extractor Macros,结合Scala String Interpolation和模式匹配来提供compile time的extractor object生成。Extractor Macros的具体用例以下:

1  import ExtractorMicros._ 2   val fname = "William"
3   val lname = "Wang"
4   val someuser =  usr"$fname,$lname"  //new FreeUser("William","Wang")
5 
6  someuser match { 7     case usr"$first,$last" => println(s"hello $first $last") 8   }

在上面这个例子里usr"???"的usr是一个pattern和extractor object。与一般的string interpolation不一样的是usr不是一个方法(method),而是一个对象(object)。这是因为模式匹配中的unapply必须在一个extractor object内,因此usr是个object。咱们知道一个object加上它的apply能够看成method来调用。也就是说若是在usr object中实现了apply就能够用usr(???)做为method使用,以下:

1   implicit class UserInterpolate(sc: StringContext) { 2     object usr { 3       def apply(args: String*): Any = macro UserMacros.appl 4       def unapply(u: User): Any = macro UserMacros.uapl 5  } 6   }

经过Def Macros在编译过程当中自动生成apply和unapply,它们分别对应了函数调用:

val someuser =  usr"$fname,$lname"

case usr"$first,$last" => println(s"hello $first $last")

下面是macro appl的实现:

1 def appl(c: Context)(args: c.Tree*) = { 2  import c.universe._ 3     val arglist = args.toList 4     q"new FreeUser(..$arglist)"
5   }

主要经过q"new FreeUser(arg1,arg2)"实现了个AST的构建。macro uapl的实现相对复杂些,对quasiquote的应用会更深刻些。首先要肯定类型的primary constructor的参数数量和名称,而后经过quasiquote的模式匹配分解出相应的sub-AST,再从新组合造成最终完整的AST:

 1 def uapl(c: Context)(u: c.Tree) = {  2  import c.universe._  3     val params = u.tpe.members.collectFirst {  4       case m: MethodSymbol if m.isPrimaryConstructor => m.asMethod  5     }.get.paramLists.head.map {p => p.asTerm.name.toString}  6 
 7     val (qget,qdef) = params.length match {  8       case len if len == 0 =>
 9         (List(q""),List(q"")) 10       case len if len == 1 =>
11         val pn = TermName(params.head) 12         (List(q"def get = u.$pn"),List(q"")) 13       case  _ =>
14         val defs = List(q"def _1 = x",q"def _2 = x",q"def _3 = x",q"def _4 = x") 15         val qdefs = (params zip defs).collect { 16           case (p,d) =>
17             val q"def $mname = $mbody" = d 18             val pn = TermName(p) 19             q"def $mname = u.$pn"
20  } 21         (List(q"def get = this"),qdefs) 22  } 23 
24       q""" 25         new { 26           class Matcher(u: User) { 27             def isEmpty = false
28  ..$qget 29  ..$qdef 30  } 31           def unapply(u: User) = new Matcher(u) 32  }.unapply($u) 33       """ 34  } 35 }

前面大部分代码就是为了造成List[Tree] qget和qdef,最后组合一个完整的quasiquote q""" new {...}"""。

完整的Macro实现源代码以下:

 1 trait User {  2  val fname: String  3  val lname: String  4 }  5 
 6 class FreeUser(val fname: String, val lname: String) extends User {  7   val i = 10
 8   def f = 1 + 2
 9 } 10 class PremiumUser(val name: String, val gender: Char, val vipnum: String) //extends User
11 
12 object ExtractorMicros { 13   implicit class UserInterpolate(sc: StringContext) { 14     object usr { 15       def apply(args: String*): Any = macro UserMacros.appl 16       def unapply(u: User): Any = macro UserMacros.uapl 17  } 18  } 19 } 20 object UserMacros { 21   def appl(c: Context)(args: c.Tree*) = { 22  import c.universe._ 23     val arglist = args.toList 24     q"new FreeUser(..$arglist)"
25  } 26   def uapl(c: Context)(u: c.Tree) = { 27  import c.universe._ 28     val params = u.tpe.members.collectFirst { 29       case m: MethodSymbol if m.isPrimaryConstructor => m.asMethod 30     }.get.paramLists.head.map {p => p.asTerm.name.toString} 31 
32     val (qget,qdef) = params.length match { 33       case len if len == 0 =>
34         (List(q""),List(q"")) 35       case len if len == 1 =>
36         val pn = TermName(params.head) 37         (List(q"def get = u.$pn"),List(q"")) 38       case  _ =>
39         val defs = List(q"def _1 = x",q"def _2 = x",q"def _3 = x",q"def _4 = x") 40         val qdefs = (params zip defs).collect { 41           case (p,d) =>
42             val q"def $mname = $mbody" = d 43             val pn = TermName(p) 44             q"def $mname = u.$pn"
45  } 46         (List(q"def get = this"),qdefs) 47  } 48 
49       q""" 50         new { 51           class Matcher(u: User) { 52             def isEmpty = false
53  ..$qget 54  ..$qdef 55  } 56           def unapply(u: User) = new Matcher(u) 57  }.unapply($u) 58       """ 59  } 60 }

调用示范代码:

 1 object Test extends App {  2  import ExtractorMicros._  3   val fname = "William"
 4   val lname = "Wang"
 5   val someuser =  usr"$fname,$lname"  //new FreeUser("William","Wang")
 6 
 7  someuser match {  8     case usr"$first,$last" => println(s"hello $first $last")  9  } 10 }

Macros Annotation(注释)是Def Macro重要的功能部分。对一个目标,包括类型、对象、方法等进行注释意思是在源代码编译时对它们进行拓展修改甚至彻底替换。好比咱们下面展现的方法注释(method annotation):假设咱们有下面两个方法:

1   def testMethod[T]: Double = { 2     val x = 2.0 + 2.0
3  Math.pow(x, x) 4  } 5 
6   def testMethodWithArgs(x: Double, y: Double) = { 7     val z = x + y 8  Math.pow(z,z) 9   }

若是我想测试它们运行所需时间的话能够在这两个方法的内部代码前设定开始时间,而后在代码后截取完成时间,完成时间-开始时间就是运算所须要的时间了,以下:

1 def testMethod[T]: Double = { 2     val start = System.nanoTime() 3     
4     val x = 2.0 + 2.0
5  Math.pow(x, x) 6     
7     val end = System.nanoTime() 8     println(s"elapsed time is: ${end - start}") 9   }

咱们但愿经过注释来拓展这个方法:具体作法是保留原来的代码,同时在方法内部先后增长几行代码。咱们看看这个注释的目的是如何实现的:

 1 def impl(c: Context)(annottees: c.Tree*): c.Tree = {  2  import c.universe._  3 
 4  annottees.head match {  5       case q"$mods def $mname[..$tpes](...$args): $rettpe = { ..$stats }" => {  6         q"""  7             $mods def $mname[..$tpes](...$args): $rettpe = {  8                val start = System.nanoTime()  9                val result = {..$stats} 10                val end = System.nanoTime() 11                println(${mname.toString} + " elapsed time in nano second = " + (end-start).toString()) 12  result 13  } 14           """ 15  } 16       case _ => c.abort(c.enclosingPosition, "Incorrect method signature!") 17     }

能够看到:咱们仍是用quasiquote来分拆被注释的方法,而后再用quasiquote重现组合这个方法。在重组过程当中增长了时间截取和列印代码。下面这行是典型的AST模式分拆(pattern desctruction):

      case q"$mods def $mname[..$tpes](...$args): $rettpe = { ..$stats }" => {...}

用这种方式把目标分拆成重组须要的最基本部分。Macro Annotation的实现源代码以下:

 1 import scala.annotation.StaticAnnotation  2 import scala.language.experimental.macros  3 import scala.reflect.macros.blackbox.Context  4 
 5 class Benchmark extends StaticAnnotation {  6   def macroTransform(annottees: Any*): Any = macro Benchmark.impl  7 }  8 object Benchmark {  9   def impl(c: Context)(annottees: c.Tree*): c.Tree = { 10  import c.universe._ 11 
12  annottees.head match { 13       case q"$mods def $mname[..$tpes](...$args): $rettpe = { ..$stats }" => { 14         q""" 15             $mods def $mname[..$tpes](...$args): $rettpe = { 16                val start = System.nanoTime() 17                val result = {..$stats} 18                val end = System.nanoTime() 19                println(${mname.toString} + " elapsed time in nano second = " + (end-start).toString()) 20  result 21  } 22           """ 23  } 24       case _ => c.abort(c.enclosingPosition, "Incorrect method signature!") 25  } 26 
27  } 28 }

注释的调用示范代码以下:

 1 object annotMethodDemo extends App {  2 
 3  @Benchmark  4   def testMethod[T]: Double = {  5     //val start = System.nanoTime()
 6 
 7     val x = 2.0 + 2.0
 8  Math.pow(x, x)  9 
10     //val end = System.nanoTime() 11     //println(s"elapsed time is: ${end - start}")
12  } 13  @Benchmark 14   def testMethodWithArgs(x: Double, y: Double) = { 15     val z = x + y 16  Math.pow(z,z) 17  } 18 
19  testMethod[String] 20   testMethodWithArgs(2.0,3.0) 21 
22 
23 }

有一点值得注意的是:Macro扩展是编译中遇到方法调用时发生的,而注释目标的扩展则在更早一步的方法声明时。咱们下面再看注释class的例子:

 1 import scala.annotation.StaticAnnotation  2 import scala.language.experimental.macros  3 import scala.reflect.macros.blackbox.Context  4 
 5 class TalkingAnimal(val voice: String) extends StaticAnnotation {  6   def macroTransform(annottees: Any*): Any = macro TalkingAnimal.implAnnot  7 }  8 
 9 object TalkingAnimal { 10   def implAnnot(c: Context)(annottees: c.Tree*): c.Tree = { 11  import c.universe._ 12 
13  annottees.head match { 14       case q"$mods class $cname[..$tparams] $ctorMods(..$params) extends Animal with ..$parents {$self => ..$stats}" =>
15         val voice = c.prefix.tree match { 16           case q"new TalkingAnimal($sound)" => c.eval[String](c.Expr(sound)) 17           case _ =>
18  c.abort(c.enclosingPosition, 19                     "TalkingAnimal must provide voice sample!") 20  } 21         val animalType = cname.toString() 22         q""" 23             $mods class $cname(..$params) extends Animal { 24  ..$stats 25               def sayHello: Unit =
26                 println("Hello, I'm a " + $animalType + " and my name is " + name + " " + $voice + "...") 27  } 28           """ 29       case _ =>
30  c.abort(c.enclosingPosition, 31                 "Annotation TalkingAnimal only apply to Animal inherited!") 32  } 33  } 34 }

咱们看到:一样仍是经过quasiquote进行AST模式拆分:

      case q"$mods class $cname[..$tparams] $ctorMods(..$params) extends Animal with ..$parents {$self => ..$stats}" =>

而后再从新组合。具体使用示范以下:

 1 object AnnotClassDemo extends App {  2  trait Animal {  3  val name: String  4  }  5   @TalkingAnimal("wangwang")  6   case class Dog(val name: String) extends Animal  7 
 8   @TalkingAnimal("miaomiao")  9   case class Cat(val name: String) extends Animal 10 
11   //@TalkingAnimal("") 12   //case class Carrot(val name: String) 13   //Error:(12,2) Annotation TalkingAnimal only apply to Animal inherited! @TalingAnimal
14   Dog("Goldy").sayHello 15   Cat("Kitty").sayHello 16 
17 }

 运算结果以下:

Hello, I'm a Dog and my name is Goldy wangwang...
Hello, I'm a Cat and my name is Kitty miaomiao...
 Process finished with exit code 0
相关文章
相关标签/搜索