前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Scala Macros - 元编程 Metaprogramming with Def Macros

Scala Macros - 元编程 Metaprogramming with Def Macros

作者头像
用户1150956
发布2018-01-05 10:58:27
3.1K0
发布2018-01-05 10:58:27
举报

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

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

代码语言:javascript
复制
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看到它们的关系:

代码语言:javascript
复制
 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目录下。

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

代码语言:javascript
复制
 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里:

代码语言:javascript
复制
1 object HelloMacro extends App {
2   import LibraryMacros._
3   greeting("john")
4 }

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

代码语言:javascript
复制
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函数。测试运行后产生结果:

代码语言:javascript
复制
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操作函数。我们在下面这个例子里使用了最新的模式和方法:

代码语言:javascript
复制
 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的调用还是一样的:

代码语言:javascript
复制
1 object HelloMacro extends App {
2   import LibraryMacros._
3   greeting("john")
4   tell("mary")
5 }

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

代码语言:javascript
复制
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:

代码语言:javascript
复制
 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:

代码语言:javascript
复制
 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

代码语言:javascript
复制
 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里:

代码语言:javascript
复制
 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的具体用例如下:

代码语言:javascript
复制
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使用,如下:

代码语言:javascript
复制
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,它们分别对应了函数调用:

代码语言:javascript
复制
val someuser =  usr"$fname,$lname"

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

下面是macro appl的实现:

代码语言:javascript
复制
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:

代码语言:javascript
复制
 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实现源代码如下:

代码语言:javascript
复制
 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 }

调用示范代码:

代码语言:javascript
复制
 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):假设我们有下面两个方法:

代码语言:javascript
复制
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   }

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

代码语言:javascript
复制
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   }

我们希望通过注释来拓展这个方法:具体做法是保留原来的代码,同时在方法内部前后增加几行代码。我们看看这个注释的目的是如何实现的:

代码语言:javascript
复制
 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):

代码语言:javascript
复制
      case q"$mods def $mname[..$tpes](...$args): $rettpe = { ..$stats }" => {...}

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

代码语言:javascript
复制
 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 }

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

代码语言:javascript
复制
 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的例子:

代码语言:javascript
复制
 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模式拆分:

代码语言:javascript
复制
      case q"$mods class $cname[..$tparams] $ctorMods(..$params) extends Animal with ..$parents {$self => ..$stats}" =>

然后再重新组合。具体使用示范如下:

代码语言:javascript
复制
 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 }

运算结果如下:

代码语言:javascript
复制
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
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-11-29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档