本文主要是介绍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 {greeting("john")}object mmacros {def greeting(person: String): Unit = macro greetingMacrodef greetingMacro(c: Context)(person: c.Expr[String]): c.Expr[Unit] = ...}
name := "learn-macro"version := "1.0.1"val commonSettings = Seq(scalaVersion := "2.11.8",scalacOptions ++= Seq("-deprecation", "-feature"),libraryDependencies ++= Seq("org.scala-lang" % "scala-reflect" % scalaVersion.value,"org.scala-lang.modules" %% "scala-parser-combinators" % "1.0.1","org.specs2" %% "specs2" % "2.3.12" % "test","org.scalatest" % "scalatest_2.11" % "2.2.1" % "test"),addCompilerPlugin("org.scalamacros" % "paradise" % "2.1.0" cross CrossVersion.full)
)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
import scala.reflect.macros.blackbox.Context
import java.util.Date
object LibraryMacros {def greeting(person: String): Unit = macro greetingMacrodef greetingMacro(c: Context)(person: c.Expr[String]): c.Expr[Unit] = {import c.universe._println("compiling greeting ...")val now = reify {new Date().toString}reify {println("Hello " + person.splice + ", the time is: " + new Date().toString)}}
}
macro调用在demo目录下的HelloMacro.scala里:
object HelloMacro extends App {import LibraryMacros._greeting("john")
}
注意在编译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
>
Hello john, the time is: Wed Nov 09 09:32:04 HKT 2016Process finished with exit code 0
运算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.tellMacroclass MacrosImpls(val c: Context) {import c.universe._def tellMacro(person: c.Tree): c.Tree = {println("compiling tell ...")val now = new Date().toStringq"""println("Hello "+$person+", it is: "+$now)"""}}
object HelloMacro extends App {import LibraryMacros._greeting("john")tell("mary")
}
测试运算产生下面的结果:
Hello john, the time is: Wed Nov 09 11:42:21 HKT 2016
Hello mary, it is: Wed Nov 09 11:42:20 HKT 2016Process finished with exit code 0
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] =implicitly[CaseClassMapConverter[C]].toMap(c)case class Person(name: String, age: Int)case class Car(make: String, year: Int, manu: String)val civic = Car("Civic",2016,"Honda")println(ccToMap[Person](Person("john",18)))println(ccToMap[Car](civic))...
Map(name -> john, age -> 18)
Map(make -> Civic, year -> 2016, manu -> Honda)
def mapTocc[C: CaseClassMapConverter](m: Map[String,Any]) =implicitly[CaseClassMapConverter[C]].fromMap(m)val mapJohn = ccToMap[Person](Person("john",18))val mapCivic = ccToMap[Car](civic)println(mapTocc[Person](mapJohn))println(mapTocc[Car](mapCivic))...
Person(john,18)
Car(Civic,2016,Honda)
我们来看看这个Macro的实现函数:macros/CaseClassConverter.scala
import scala.language.experimental.macros
import scala.reflect.macros.whitebox.Contexttrait CaseClassMapConverter[C] {def toMap(c: C): Map[String,Any]def fromMap(m: Map[String,Any]): C
}
object CaseClassMapConverter {implicit def Materializer[C]: CaseClassMapConverter[C] = macro converterMacro[C]def converterMacro[C: c.WeakTypeTag](c: Context): c.Tree = {import c.universe._val tpe = weakTypeOf[C]val fields = tpe.decls.collectFirst {case m: MethodSymbol if m.isPrimaryConstructor => m}.get.paramLists.headval companion = tpe.typeSymbol.companionval (toParams,fromParams) = fields.map { field =>val name = field.name.toTermNameval decoded = name.decodedName.toStringval rtype = tpe.decl(name).typeSignature(q"$decoded -> t.$name", q"map($decoded).asInstanceOf[$rtype]")}.unzipq"""new CaseClassMapConverter[$tpe] {def toMap(t: $tpe): Map[String,Any] = Map(..$toParams)def fromMap(map: Map[String,Any]): $tpe = $companion(..$fromParams)}"""}
}
import CaseClassMapConverter._
object ConvertDemo extends App {def ccToMap[C: CaseClassMapConverter](c: C): Map[String,Any] =implicitly[CaseClassMapConverter[C]].toMap(c)case class Person(name: String, age: Int)case class Car(make: String, year: Int, manu: String)val civic = Car("Civic",2016,"Honda")//println(ccToMap[Person](Person("john",18)))//println(ccToMap[Car](civic))def mapTocc[C: CaseClassMapConverter](m: Map[String,Any]) =implicitly[CaseClassMapConverter[C]].fromMap(m)val mapJohn = ccToMap[Person](Person("john",18))val mapCivic = ccToMap[Car](civic)println(mapTocc[Person](mapJohn))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._val fname = "William"val lname = "Wang"val someuser = usr"$fname,$lname" //new FreeUser("William","Wang")someuser match {case usr"$first,$last" => println(s"hello $first $last")}
implicit class UserInterpolate(sc: StringContext) {object usr {def apply(args: String*): Any = macro UserMacros.appldef unapply(u: User): Any = macro UserMacros.uapl}}
val someuser = usr"$fname,$lname"case usr"$first,$last" => println(s"hello $first $last")
def appl(c: Context)(args: c.Tree*) = {import c.universe._val arglist = args.toListq"new FreeUser(..$arglist)"}
def uapl(c: Context)(u: c.Tree) = {import c.universe._val params = u.tpe.members.collectFirst {case m: MethodSymbol if m.isPrimaryConstructor => m.asMethod}.get.paramLists.head.map {p => p.asTerm.name.toString}val (qget,qdef) = params.length match {case len if len == 0 =>(List(q""),List(q""))case len if len == 1 =>val pn = TermName(params.head)(List(q"def get = u.$pn"),List(q""))case _ =>val defs = List(q"def _1 = x",q"def _2 = x",q"def _3 = x",q"def _4 = x")val qdefs = (params zip defs).collect {case (p,d) =>val q"def $mname = $mbody" = dval pn = TermName(p)q"def $mname = u.$pn"}(List(q"def get = this"),qdefs)}q"""new {class Matcher(u: User) {def isEmpty = false..$qget..$qdef}def unapply(u: User) = new Matcher(u)}.unapply($u)"""}
}
完整的Macro实现源代码如下:
trait User {val fname: Stringval lname: String
}class FreeUser(val fname: String, val lname: String) extends User {val i = 10def f = 1 + 2
}
class PremiumUser(val name: String, val gender: Char, val vipnum: String) //extends Userobject ExtractorMicros {implicit class UserInterpolate(sc: StringContext) {object usr {def apply(args: String*): Any = macro UserMacros.appldef unapply(u: User): Any = macro UserMacros.uapl}}
}
object UserMacros {def appl(c: Context)(args: c.Tree*) = {import c.universe._val arglist = args.toListq"new FreeUser(..$arglist)"}def uapl(c: Context)(u: c.Tree) = {import c.universe._val params = u.tpe.members.collectFirst {case m: MethodSymbol if m.isPrimaryConstructor => m.asMethod}.get.paramLists.head.map {p => p.asTerm.name.toString}val (qget,qdef) = params.length match {case len if len == 0 =>(List(q""),List(q""))case len if len == 1 =>val pn = TermName(params.head)(List(q"def get = u.$pn"),List(q""))case _ =>val defs = List(q"def _1 = x",q"def _2 = x",q"def _3 = x",q"def _4 = x")val qdefs = (params zip defs).collect {case (p,d) =>val q"def $mname = $mbody" = dval pn = TermName(p)q"def $mname = u.$pn"}(List(q"def get = this"),qdefs)}q"""new {class Matcher(u: User) {def isEmpty = false..$qget..$qdef}def unapply(u: User) = new Matcher(u)}.unapply($u)"""}
}
调用示范代码:
object Test extends App {import ExtractorMicros._val fname = "William"val lname = "Wang"val someuser = usr"$fname,$lname" //new FreeUser("William","Wang")someuser match {case usr"$first,$last" => println(s"hello $first $last")}
}
Macros Annotation(注释)是Def Macro重要的功能部分。对一个目标,包括类型、对象、方法等进行注释意思是在源代码编译时对它们进行拓展修改甚至完全替换。比如我们下面展示的方法注释(method annotation):假设我们有下面两个方法:
def testMethod[T]: Double = {val x = 2.0 + 2.0Math.pow(x, x)}def testMethodWithArgs(x: Double, y: Double) = {val z = x + yMath.pow(z,z)}
如果我想测试它们运行所需时间的话可以在这两个方法的内部代码前设定开始时间,然后在代码后截取完成时间,完成时间-开始时间就是运算所需要的时间了,如下:
def testMethod[T]: Double = {val start = System.nanoTime()val x = 2.0 + 2.0Math.pow(x, x)val end = System.nanoTime()println(s"elapsed time is: ${end - start}")}
def impl(c: Context)(annottees: c.Tree*): c.Tree = {import c.universe._annottees.head match {case q"$mods def $mname[..$tpes](...$args): $rettpe = { ..$stats }" => {q"""$mods def $mname[..$tpes](...$args): $rettpe = {val start = System.nanoTime()val result = {..$stats}val end = System.nanoTime()println(${mname.toString} + " elapsed time in nano second = " + (end-start).toString())result}"""}case _ => c.abort(c.enclosingPosition, "Incorrect method signature!")}
case q"$mods def $mname[..$tpes](...$args): $rettpe = { ..$stats }" => {...}
import scala.annotation.StaticAnnotation
import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Contextclass Benchmark extends StaticAnnotation {def macroTransform(annottees: Any*): Any = macro Benchmark.impl
}
object Benchmark {def impl(c: Context)(annottees: c.Tree*): c.Tree = {import c.universe._annottees.head match {case q"$mods def $mname[..$tpes](...$args): $rettpe = { ..$stats }" => {q"""$mods def $mname[..$tpes](...$args): $rettpe = {val start = System.nanoTime()val result = {..$stats}val end = System.nanoTime()println(${mname.toString} + " elapsed time in nano second = " + (end-start).toString())result}"""}case _ => c.abort(c.enclosingPosition, "Incorrect method signature!")}}
}
object annotMethodDemo extends App {@Benchmarkdef testMethod[T]: Double = {//val start = System.nanoTime()val x = 2.0 + 2.0Math.pow(x, x)//val end = System.nanoTime()//println(s"elapsed time is: ${end - start}")}@Benchmarkdef testMethodWithArgs(x: Double, y: Double) = {val z = x + yMath.pow(z,z)}testMethod[String]testMethodWithArgs(2.0,3.0)}
有一点值得注意的是:Macro扩展是编译中遇到方法调用时发生的,而注释目标的扩展则在更早一步的方法声明时。我们下面再看一个注释class的例子:
import scala.annotation.StaticAnnotation
import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Contextclass TalkingAnimal(val voice: String) extends StaticAnnotation {def macroTransform(annottees: Any*): Any = macro TalkingAnimal.implAnnot
}object TalkingAnimal {def implAnnot(c: Context)(annottees: c.Tree*): c.Tree = {import c.universe._annottees.head match {case q"$mods class $cname[..$tparams] $ctorMods(..$params) extends Animal with ..$parents {$self => ..$stats}" =>val voice = c.prefix.tree match {case q"new TalkingAnimal($sound)" => c.eval[String](c.Expr(sound))case _ =>c.abort(c.enclosingPosition,"TalkingAnimal must provide voice sample!")}val animalType = cname.toString()q"""$mods class $cname(..$params) extends Animal {..$statsdef sayHello: Unit =println("Hello, I'm a " + $animalType + " and my name is " + name + " " + $voice + "...")}"""case _ =>c.abort(c.enclosingPosition,"Annotation TalkingAnimal only apply to Animal inherited!")}}
}
我们看到:同样还是通过quasiquote进行AST模式拆分:
case q"$mods class $cname[..$tparams] $ctorMods(..$params) extends Animal with ..$parents {$self => ..$stats}" =>
object AnnotClassDemo extends App {trait Animal {val name: String}@TalkingAnimal("wangwang")case class Dog(val name: String) extends Animal@TalkingAnimal("miaomiao")case class Cat(val name: String) extends Animal//@TalkingAnimal("")//case class Carrot(val name: String)//Error:(12,2) Annotation TalkingAnimal only apply to Animal inherited! @TalingAnimalDog("Goldy").sayHelloCat("Kitty").sayHello}
运算结果如下:
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
这篇关于Scala Macros - 元编程 Metaprogramming with Def Macros的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!