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开始继续进行类型验证过程。
下面我们先用个简单的例子来示范分析一下Def Macros的基本原理和使用方法:
object modules {<br/> greeting("john")<br/> } object mmacros {<br/> def greeting(person: String): Unit = macro greetingMacro<br/> def greetingMacro(c: Context)(person: c.Expr[String]): c.Expr[Unit] = ...<br/> }
以上是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看到它们的关系:
name := "learn-macro" version := "1.0.1" val commonSettings = Seq(<br/> scalaVersion := "2.11.8",<br/> scalacOptions ++= Seq("-deprecation", "-feature"),<br/> libraryDependencies ++= Seq(<br/> "org.scala-lang" % "scala-reflect" % scalaVersion.value,<br/> "org.scala-lang.modules" %% "scala-parser-combinators" % "1.0.1",<br/> "org.specs2" %% "specs2" % "2.3.12" % "test",<br/> "org.scalatest" % "scalatest_2.11" % "2.2.1" % "test"<br/> ),<br/> addCompilerPlugin("org.scalamacros" % "paradise" % "2.1.0" cross CrossVersion.full)<br/> ) lazy val root = (project in file(".")).aggregate(macros, demos) lazy val macros = project.in(file("macros")).settings(commonSettings : _*) lazy val demos = project.in(file("demos")).settings(commonSettings : _*).dependsOn(macros)
注意最后一行:demos dependsOn(macros),因为我们会把所有macros定义文件放在macros目录下。
下面我们来看看macro的具体实现方法:
import scala.language.experimental.macros<br/> import scala.reflect.macros.blackbox.Context<br/> import java.util.Date<br/> object LibraryMacros {<br/> def greeting(person: String): Unit = macro greetingMacro def greetingMacro(c: Context)(person: c.Expr[String]): c.Expr[Unit] = {<br/> import c.universe._<br/> println("compiling greeting ...")<br/> val now = reify {new Date().toString}<br/> reify {<br/> println("Hello " + person.splice + ", the time is: " + new Date().toString)<br/> }<br/> }<br/> }
以上是macro greeting的具体声明和实现。代码放在macros目录下的MacrosLibrary.scala里。首先必须import macros和Context。
macro调用在demo目录下的HelloMacro.scala里:
object HelloMacro extends App {<br/> import LibraryMacros._<br/> greeting("john")<br/> }
注意在编译HelloMacro.scala时产生的输出:
Mac-Pro:learn-macro tiger-macpro$ sbt<br/> [info] Loading global plugins from /Users/tiger-macpro/.sbt/0.13/plugins<br/> [info] Loading project definition from /Users/tiger-macpro/Scala/IntelliJ/learn-macro/project<br/> [info] Set current project to learn-macro (in build file:/Users/tiger-macpro/Scala/IntelliJ/learn-macro/)<br/> > project demos<br/> [info] Set current project to demos (in build file:/Users/tiger-macpro/Scala/IntelliJ/learn-macro/)<br/> > compile<br/> [info] Compiling Scala source to /Users/tiger-macpro/Scala/IntelliJ/learn-macro/macros/target/scala-2.11/classes...<br/> [info] 'compiler-interface' not yet compiled for Scala 2.11.. Compiling...<br/> [info] Compilation completed in 7.876 s<br/> [info] Compiling Scala source to /Users/tiger-macpro/Scala/IntelliJ/learn-macro/demos/target/scala-2.11/classes...<br/> compiling greeting ...<br/> [success] Total time: s, completed -- ::<br/> >
从compiling greeting …这条提示我们可以得出在编译demo目录下源代码文件的过程中应该运算了greetingMacro函数。测试运行后产生结果:
Hello john, the time is: Wed Nov :: HKT Process finished with exit code
运算greeting实际上是调用了greetingMacro中的macro实现代码。上面这个例子使用了最基础的Scala Macro编程模式。注意这个例子里函数greetingMacro的参数c: Context和在函数内部代码中reify,splice的调用:由于Context是个动态函数接口,每个实例都有所不同。对于大型的macro实现函数,可能会调用到其它同样会使用到Context的辅助函数(helper function),容易出现Context实例不匹配问题。另外reify和splice可以说是最原始的AST操作函数。我们在下面这个例子里使用了最新的模式和方法:
def tell(person: String): Unit = macro MacrosImpls.tellMacro<br/> class MacrosImpls(val c: Context) {<br/> import c.universe._<br/> def tellMacro(person: c.Tree): c.Tree = {<br/> println("compiling tell ...")<br/> val now = new Date().toString<br/> q"""<br/> println("Hello "+$person+", it is: "+$now)<br/> """<br/> }<br/> }
在这个例子里我们把macro实现函数放入一个以Context为参数的class。我们可以把所有使用Context的函数都摆在这个class里面大家共用统一的Context实例。quasiquotes是最新的AST操作函数集,可以更方便灵活地控制AST的产生、表达式还原等。这个tell macro的调用还是一样的:
object HelloMacro extends App {<br/> import LibraryMacros._<br/> greeting("john")<br/> tell("mary")<br/> }
测试运算产生下面的结果:
Hello john, the time is: Wed Nov :: HKT<br/> Hello mary, it is: Wed Nov :: HKT Process finished with exit code
Def Macros的Macro实现函数可以是泛型函数,支持类参数。在下面的例子我们示范如何用Def Macros来实现通用的case class与Map类型的转换。假设我们有个转换器CaseClassMapConverter[C],那么C类型可以是任何case class,所以这个转换器是泛型的,那么macro实现函数也就必须是泛型的了。大体来说,我们希望实现以下功能:把任何case class转成Map:
def ccToMap[C: CaseClassMapConverter](c: C): Map[String,Any] =<br/> implicitly[CaseClassMapConverter[C]].toMap(c) case class Person(name: String, age: Int)<br/> case class Car(make: String, year: Int, manu: String) val civic = Car("Civic",,"Honda")<br/> println(ccToMap[Person](Person("john",)))<br/> println(ccToMap[Car](civic)) ...<br/> Map(name -> john, age -> )<br/> Map(make -> Civic, year -> , manu -> Honda)
反向把Map转成case class:
def mapTocc[C: CaseClassMapConverter](m: Map[String,Any]) =<br/> implicitly[CaseClassMapConverter[C]].fromMap(m) val mapJohn = ccToMap[Person](Person("john",))<br/> val mapCivic = ccToMap[Car](civic)<br/> println(mapTocc[Person](mapJohn))<br/> println(mapTocc[Car](mapCivic)) ...<br/> Person(john,)<br/> Car(Civic,,Honda)
我们来看看这个Macro的实现函数:macros/CaseClassConverter.scala
import scala.language.experimental.macros<br/> import scala.reflect.macros.whitebox.Context trait CaseClassMapConverter[C] {<br/> def toMap(c: C): Map[String,Any]<br/> def fromMap(m: Map[String,Any]): C<br/> }<br/> object CaseClassMapConverter {<br/> implicit def Materializer[C]: CaseClassMapConverter[C] = macro converterMacro[C]<br/> def converterMacro[C: c.WeakTypeTag](c: Context): c.Tree = {<br/> import c.universe._ val tpe = weakTypeOf[C]<br/> val fields = tpe.decls.collectFirst {<br/> case m: MethodSymbol if m.isPrimaryConstructor => m<br/> }.get.paramLists.head val companion = tpe.typeSymbol.companion<br/> val (toParams,fromParams) = fields.map { field =><br/> val name = field.name.toTermName<br/> val decoded = name.decodedName.toString<br/> val rtype = tpe.decl(name).typeSignature (q"$decoded -> t.$name", q"map($decoded).asInstanceOf[$rtype]") }.unzip q"""<br/> new CaseClassMapConverter[$tpe] {<br/> def toMap(t: $tpe): Map[String,Any] = Map(..$toParams)<br/> def fromMap(map: Map[String,Any]): $tpe = $companion(..$fromParams)<br/> }<br/> """<br/> }<br/> }
首先,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里:
import CaseClassMapConverter._<br/> object ConvertDemo extends App { def ccToMap[C: CaseClassMapConverter](c: C): Map[String,Any] =<br/> implicitly[CaseClassMapConverter[C]].toMap(c) case class Person(name: String, age: Int)<br/> case class Car(make: String, year: Int, manu: String) val civic = Car("Civic",,"Honda")<br/> //println(ccToMap[Person](Person("john",18)))<br/> //println(ccToMap[Car](civic)) def mapTocc[C: CaseClassMapConverter](m: Map[String,Any]) =<br/> implicitly[CaseClassMapConverter[C]].fromMap(m) val mapJohn = ccToMap[Person](Person("john",))<br/> val mapCivic = ccToMap[Car](civic)<br/> println(mapTocc[Person](mapJohn))<br/> println(mapTocc[Car](mapCivic)) }
在上面这个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的具体用例如下:
import ExtractorMicros._<br/> val fname = "William"<br/> val lname = "Wang"<br/> val someuser = usr"$fname,$lname" //new FreeUser("William","Wang") someuser match {<br/> case usr"$first,$last" => println(s"hello $first $last")<br/> }
在上面这个例子里usr”???”的usr是一个pattern和extractor object。与通常的string interpolation不同的是usr不是一个方法(method),而是一个对象(object)。这是由于模式匹配中的unapply必须在一个extractor object内,所以usr是个object。我们知道一个object加上它的apply可以当作method来调用。也就是说如果在usr object中实现了apply就可以用usr(???)作为method使用,如下:
implicit class UserInterpolate(sc: StringContext) {<br/> object usr {<br/> def apply(args: String*): Any = macro UserMacros.appl<br/> def unapply(u: User): Any = macro UserMacros.uapl<br/> }<br/> }
通过Def Macros在编译过程中自动生成apply和unapply,它们分别对应了函数调用:
val someuser = usr"$fname,$lname" case usr"$first,$last" => println(s"hello $first $last")
下面是macro appl的实现:
def appl(c: Context)(args: c.Tree*) = {<br/> import c.universe._<br/> val arglist = args.toList<br/> q"new FreeUser(..$arglist)"<br/> }
主要通过q”new FreeUser(arg1,arg2)”实现了个AST的构建。macro uapl的实现相对复杂些,对quasiquote的应用会更深入些。首先要确定类型的primary constructor的参数数量和名称,然后通过quasiquote的模式匹配分解出相应的sub-AST,再重新组合形成最终完整的AST:
def uapl(c: Context)(u: c.Tree) = {<br/> import c.universe._<br/> val params = u.tpe.members.collectFirst {<br/> case m: MethodSymbol if m.isPrimaryConstructor => m.asMethod<br/> }.get.paramLists.head.map {p => p.asTerm.name.toString} val (qget,qdef) = params.length match {<br/> case len if len == =><br/> (List(q""),List(q""))<br/> case len if len == =><br/> val pn = TermName(params.head)<br/> (List(q"def get = u.$pn"),List(q""))<br/> case _ =><br/> val defs = List(q"def _1 = x",q"def _2 = x",q"def _3 = x",q"def _4 = x")<br/> val qdefs = (params zip defs).collect {<br/> case (p,d) =><br/> val q"def $mname = $mbody" = d<br/> val pn = TermName(p)<br/> q"def $mname = u.$pn"<br/> }<br/> (List(q"def get = this"),qdefs)<br/> } q"""<br/> new {<br/> class Matcher(u: User) {<br/> def isEmpty = false<br/> ..$qget<br/> ..$qdef<br/> }<br/> def unapply(u: User) = new Matcher(u)<br/> }.unapply($u)<br/> """<br/> }<br/> }
前面大部分代码就是为了形成List[Tree] qget和qdef,最后组合一个完整的quasiquote q””” new {…}”””。
完整的Macro实现源代码如下:
trait User {<br/> val fname: String<br/> val lname: String<br/> } class FreeUser(val fname: String, val lname: String) extends User {<br/> val i =<br/> def f = +<br/> }<br/> class PremiumUser(val name: String, val gender: Char, val vipnum: String) //extends User object ExtractorMicros {<br/> implicit class UserInterpolate(sc: StringContext) {<br/> object usr {<br/> def apply(args: String*): Any = macro UserMacros.appl<br/> def unapply(u: User): Any = macro UserMacros.uapl<br/> }<br/> }<br/> }<br/> object UserMacros {<br/> def appl(c: Context)(args: c.Tree*) = {<br/> import c.universe._<br/> val arglist = args.toList<br/> q"new FreeUser(..$arglist)"<br/> }<br/> def uapl(c: Context)(u: c.Tree) = {<br/> import c.universe._<br/> val params = u.tpe.members.collectFirst {<br/> case m: MethodSymbol if m.isPrimaryConstructor => m.asMethod<br/> }.get.paramLists.head.map {p => p.asTerm.name.toString} val (qget,qdef) = params.length match {<br/> case len if len == =><br/> (List(q""),List(q""))<br/> case len if len == =><br/> val pn = TermName(params.head)<br/> (List(q"def get = u.$pn"),List(q""))<br/> case _ =><br/> val defs = List(q"def _1 = x",q"def _2 = x",q"def _3 = x",q"def _4 = x")<br/> val qdefs = (params zip defs).collect {<br/> case (p,d) =><br/> val q"def $mname = $mbody" = d<br/> val pn = TermName(p)<br/> q"def $mname = u.$pn"<br/> }<br/> (List(q"def get = this"),qdefs)<br/> } q"""<br/> new {<br/> class Matcher(u: User) {<br/> def isEmpty = false<br/> ..$qget<br/> ..$qdef<br/> }<br/> def unapply(u: User) = new Matcher(u)<br/> }.unapply($u)<br/> """<br/> }<br/> }
调用示范代码:
object Test extends App {<br/> import ExtractorMicros._<br/> val fname = "William"<br/> val lname = "Wang"<br/> val someuser = usr"$fname,$lname" //new FreeUser("William","Wang") someuser match {<br/> case usr"$first,$last" => println(s"hello $first $last")<br/> }<br/> }
Macros Annotation(注释)是Def Macro重要的功能部分。对一个目标,包括类型、对象、方法等进行注释意思是在源代码编译时对它们进行拓展修改甚至完全替换。比如我们下面展示的方法注释(method annotation):假设我们有下面两个方法:
def testMethod[T]: Double = {<br/> val x = 2.0 + 2.0<br/> Math.pow(x, x)<br/> } def testMethodWithArgs(x: Double, y: Double) = {<br/> val z = x + y<br/> Math.pow(z,z)<br/> }
如果我想测试它们运行所需时间的话可以在这两个方法的内部代码前设定开始时间,然后在代码后截取完成时间,完成时间-开始时间就是运算所需要的时间了,如下:
def testMethod[T]: Double = {<br/> val start = System.nanoTime() val x = 2.0 + 2.0<br/> Math.pow(x, x) val end = System.nanoTime()<br/> println(s"elapsed time is: ${end - start}")<br/> }
我们希望通过注释来拓展这个方法:具体做法是保留原来的代码,同时在方法内部前后增加几行代码。我们看看这个注释的目的是如何实现的:
def impl(c: Context)(annottees: c.Tree*): c.Tree = {<br/> import c.universe._ annottees.head match {<br/> case q"$mods def $mname[..$tpes](...$args): $rettpe = { ..$stats }" => {<br/> q"""<br/> $mods def $mname[..$tpes](...$args): $rettpe = {<br/> val start = System.nanoTime()<br/> val result = {..$stats}<br/> val end = System.nanoTime()<br/> println(${mname.toString} + " elapsed time in nano second = " + (end-start).toString())<br/> result<br/> }<br/> """<br/> }<br/> case _ => c.abort(c.enclosingPosition, "Incorrect method signature!")<br/> }
可以看到:我们还是用quasiquote来分拆被注释的方法,然后再用quasiquote重现组合这个方法。在重组过程中增加了时间截取和列印代码。下面这行是典型的AST模式分拆(pattern desctruction):
case q"$mods def $mname[..$tpes](...$args): $rettpe = { ..$stats }" => {...}
用这种方式把目标分拆成重组需要的最基本部分。Macro Annotation的实现源代码如下:
import scala.annotation.StaticAnnotation<br/> import scala.language.experimental.macros<br/> import scala.reflect.macros.blackbox.Context class Benchmark extends StaticAnnotation {<br/> def macroTransform(annottees: Any*): Any = macro Benchmark.impl<br/> }<br/> object Benchmark {<br/> def impl(c: Context)(annottees: c.Tree*): c.Tree = {<br/> import c.universe._ annottees.head match {<br/> case q"$mods def $mname[..$tpes](...$args): $rettpe = { ..$stats }" => {<br/> q"""<br/> $mods def $mname[..$tpes](...$args): $rettpe = {<br/> val start = System.nanoTime()<br/> val result = {..$stats}<br/> val end = System.nanoTime()<br/> println(${mname.toString} + " elapsed time in nano second = " + (end-start).toString())<br/> result<br/> }<br/> """<br/> }<br/> case _ => c.abort(c.enclosingPosition, "Incorrect method signature!")<br/> } }<br/> }
注释的调用示范代码如下:
object annotMethodDemo extends App { @Benchmark<br/> def testMethod[T]: Double = {<br/> //val start = System.nanoTime() val x = 2.0 + 2.0<br/> Math.pow(x, x) //val end = System.nanoTime()<br/> //println(s"elapsed time is: ${end - start}")<br/> }<br/> @Benchmark<br/> def testMethodWithArgs(x: Double, y: Double) = {<br/> val z = x + y<br/> Math.pow(z,z)<br/> } testMethod[String]<br/> testMethodWithArgs(2.0,3.0) }
有一点值得注意的是:Macro扩展是编译中遇到方法调用时发生的,而注释目标的扩展则在更早一步的方法声明时。我们下面再看注释class的例子:
import scala.annotation.StaticAnnotation<br/> import scala.language.experimental.macros<br/> import scala.reflect.macros.blackbox.Context class TalkingAnimal(val voice: String) extends StaticAnnotation {<br/> def macroTransform(annottees: Any*): Any = macro TalkingAnimal.implAnnot<br/> } object TalkingAnimal {<br/> def implAnnot(c: Context)(annottees: c.Tree*): c.Tree = {<br/> import c.universe._ annottees.head match {<br/> case q"$mods class $cname[..$tparams] $ctorMods(..$params) extends Animal with ..$parents {$self => ..$stats}" =><br/> val voice = c.prefix.tree match {<br/> case q"new TalkingAnimal($sound)" => c.eval[String](c.Expr(sound))<br/> case _ =><br/> c.abort(c.enclosingPosition,<br/> "TalkingAnimal must provide voice sample!")<br/> }<br/> val animalType = cname.toString()<br/> q"""<br/> $mods class $cname(..$params) extends Animal {<br/> ..$stats<br/> def sayHello: Unit =<br/> println("Hello, I'm a " + $animalType + " and my name is " + name + " " + $voice + "...")<br/> }<br/> """<br/> case _ =><br/> c.abort(c.enclosingPosition,<br/> "Annotation TalkingAnimal only apply to Animal inherited!")<br/> }<br/> }<br/> }
我们看到:同样还是通过quasiquote进行AST模式拆分:
case q"$mods class $cname[..$tparams] $ctorMods(..$params) extends Animal with ..$parents {$self => ..$stats}" =>
然后再重新组合。具体使用示范如下:
object AnnotClassDemo extends App {<br/> trait Animal {<br/> val name: String<br/> }<br/> @TalkingAnimal("wangwang")<br/> case class Dog(val name: String) extends Animal @TalkingAnimal("miaomiao")<br/> case class Cat(val name: String) extends Animal //@TalkingAnimal("")<br/> //case class Carrot(val name: String)<br/> //Error:(12,2) Annotation TalkingAnimal only apply to Animal inherited! @TalingAnimal<br/> Dog("Goldy").sayHello<br/> Cat("Kitty").sayHello }
运算结果如下:
Hello, I'm a Dog and my name is Goldy wangwang...<br/> Hello, I'm a Cat and my name is Kitty miaomiao... Process finished with exit code
转发申明:
本文转自互联网,由小站整理并发布,在于分享相关技术和知识。版权归原作者所有,如有侵权,请联系本站 top8488@163.com,将在24小时内删除。谢谢