本文整理汇总了Scala中scala.reflect.macros.blackbox类的典型用法代码示例。如果您正苦于以下问题:Scala blackbox类的具体用法?Scala blackbox怎么用?Scala blackbox使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了blackbox类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: GitInfo
//设置package包名称以及导入依赖的类
package git
import java.util.Date
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.storage.file.FileRepositoryBuilder
import scala.language.experimental.macros
import scala.reflect.macros.blackbox
import scala.collection.JavaConversions._
object GitInfo {
def lastRevCommitName(): String = macro lastRevCommitName_impl
def lastRevCommitName_impl(c: blackbox.Context)(): c.Expr[String] = {
val git = Git.wrap(loadGitRepositoryfromEnclosingSourcePosition(c))
import c.universe._
c.Expr[String](q""" ${lastRevCommitName(git)} """)
}
def lastRevCommitAuthor(): String = macro lastRevCommitAuthor_impl
def lastRevCommitAuthor_impl(c: blackbox.Context)(): c.Expr[String] = {
val git = Git.wrap(loadGitRepositoryfromEnclosingSourcePosition(c))
import c.universe._
c.Expr[String](q""" ${lastRevCommitAuthorName(git)} """)
}
def currentBranch(): String = macro currentBranch_impl
def currentBranch_impl(c: blackbox.Context)(): c.Expr[String] = {
import c.universe._
c.Expr[String](q""" ${loadGitRepositoryfromEnclosingSourcePosition(c).getBranch}""")
}
def lastRevCommitMessage(): String = macro lastRevCommitMessage_impl
def lastRevCommitMessage_impl(c: blackbox.Context)(): c.Expr[String] = {
import c.universe._
val git = Git.wrap(loadGitRepositoryfromEnclosingSourcePosition(c))
c.Expr[String](q""" ${lastRevCommitMessage(git)} """)
}
def lastRevCommitTime(): String = macro lastRevCommitTime_impl
def lastRevCommitTime_impl(c: blackbox.Context)(): c.Expr[String] = {
import c.universe._
val git = Git.wrap(loadGitRepositoryfromEnclosingSourcePosition(c))
c.Expr[String](q""" ${lastRevCommitDate(git)} """)
}
}
示例2: CoreMacros
//设置package包名称以及导入依赖的类
package com.outr.arango
import scala.annotation.compileTimeOnly
import scala.language.experimental.macros
import scala.reflect.macros.blackbox
@compileTimeOnly("Enable macro paradise to expand compile-time macros")
object CoreMacros {
def updateIfModifiable[T](c: blackbox.Context)(value: c.Expr[T])(implicit t: c.WeakTypeTag[T]): c.Expr[T] = {
import c.universe._
if (t.tpe <:< typeOf[Modifiable]) {
c.Expr[T](q"$value.copy(modified = System.currentTimeMillis())")
} else {
c.Expr[T](q"$value")
}
}
}
示例3: RuleMacros
//设置package包名称以及导入依赖的类
package checklist
import scala.language.experimental.macros
import scala.language.higherKinds
import scala.reflect.macros.blackbox
class RuleMacros(val c: blackbox.Context) {
import c.universe._
def field[A: c.WeakTypeTag, B: c.WeakTypeTag](accessor: c.Tree)(rule: c.Tree): c.Tree = {
val q"($param) => $rhs" = accessor
val a = weakTypeOf[A]
val b = weakTypeOf[B]
val path = accessorPrefix(accessor)
val lens = q"""monocle.macros.GenLens[$a].apply[$b]($accessor)"""
q"${c.prefix}.field($path, $lens)($rule)"
}
def fieldWith[A: c.WeakTypeTag, B: c.WeakTypeTag](accessor: c.Tree)(builder: c.Tree): c.Tree = {
val a = weakTypeOf[A]
val b = weakTypeOf[B]
val path = accessorPrefix(accessor)
val lens = q"""monocle.macros.GenLens[$a].apply[$b]($accessor)"""
q"${c.prefix}.fieldWith($path, $lens)($builder)"
}
private def accessorPrefix(accessor: c.Tree): Tree = {
def fail = c.abort(c.enclosingPosition, errorMessage(s"Argument is not an accessor function literal."))
@scala.annotation.tailrec
def unpack(expr: Tree, accum: List[String]): Tree =
expr match {
case Ident(_) => accum.foldRight(q"_root_.checklist.PNil" : Tree)((a, b) => q"$a :: $b")
case Select(a, TermName(b)) => unpack(a, b :: accum)
case _ => fail
}
accessor match {
case q"($param) => $rhs" => unpack(rhs, Nil)
case other => fail
}
}
private def errorMessage(prefix: String) =
s"""
|$prefix
|
|The argument must be a function literal of the form `_.field`.
|Alternatively use the `rule.field(path, lens)(rule)` method,
|which allows you to specify the field name manually.
""".stripMargin
}
示例4: ProcessorGenerator
//设置package包名称以及导入依赖的类
package com.outr.iconsole
import scala.language.experimental.macros
import scala.reflect.macros.blackbox
object ProcessorGenerator {
def registerFromObject[T](c: blackbox.Context)(module: c.Expr[Option[String]], obj: c.Expr[T])(implicit t: c.WeakTypeTag[T]): c.Expr[List[CommandProcessor]] = {
import c.universe._
val processors = processorsFor[T](c)(module, obj)(t)
c.Expr[List[CommandProcessor]](
q"""
$processors.foreach { p =>
com.outr.iconsole.CommandProcessor.register(p)
}
$processors
""")
}
def processorsFor[T](c: blackbox.Context)(module: c.Expr[Option[String]], obj: c.Expr[T])(implicit t: c.WeakTypeTag[T]): c.Expr[List[CommandProcessor]] = {
import c.universe._
val members = weakTypeOf[T].decls
val methods = members.filter { m =>
val term = m.asTerm
term.isMethod && !term.isConstructor && term.isPublic && !m.name.decodedName.toString.contains("$default$")
}
val defaultArgs = members.filter { m =>
val term = m.asTerm
term.isMethod && !term.isConstructor && term.isPublic && m.name.decodedName.toString.contains("$default$")
}.map(m => m.name.decodedName.toString -> m).toMap
val commandProcessors = methods.map { m =>
val name = m.name.decodedName.toString
val paramList = m.info.paramLists.head
val params = paramList.zipWithIndex.map {
case (param, index) => {
val paramName = param.name.decodedName.toString
val paramType = param.info.resultType
val defaultArg = defaultArgs.get(s"$name$$default$$${index + 1}").map(m => q"$m")
q"com.outr.iconsole.ProcessorGenerator.extractArg[$paramType](command, $paramName, $index, $defaultArg)"
}
}
q"""
import com.outr.iconsole._
CommandProcessor($module, $name) { command =>
$m(..$params)
}
"""
}
c.Expr[List[CommandProcessor]](q"List(..$commandProcessors)")
}
def extractArg[T](command: Command, name: String, index: Int, default: => Option[T])(implicit string2T: String => T): T = {
val s = command.args.get(name).orElse(command.args.get(s"arg${index + 1}"))
s.map(string2T).orElse(default).getOrElse(throw new RuntimeException(s"No argument provided $name (index: $index)."))
}
}
示例5: requireArg
//设置package包名称以及导入依赖的类
package swave.core
import scala.reflect.macros.blackbox
package object macros {
def requireArg(cond: Boolean): Unit = macro Macros.requireArgImpl
def requireArg(cond: Boolean, msg: Any): Unit = macro Macros.requireArg1Impl
def requireState(cond: Boolean): Unit = macro Macros.requireStateImpl
def requireState(cond: Boolean, msg: Any): Unit = macro Macros.requireState1Impl
}
package macros {
private[macros] object Macros {
def requireArgImpl(c: blackbox.Context)(cond: c.Expr[Boolean]): c.Expr[Unit] = {
import c.universe._
reify {
if (!cond.splice) throw new IllegalArgumentException
}
}
def requireArg1Impl(c: blackbox.Context)(cond: c.Expr[Boolean], msg: c.Expr[Any]): c.Expr[Unit] = {
import c.universe._
reify {
if (!cond.splice) {
throw new IllegalArgumentException(msg.splice.toString)
}
}
}
def requireStateImpl(c: blackbox.Context)(cond: c.Expr[Boolean]): c.Expr[Unit] = {
import c.universe._
reify {
if (!cond.splice) {
throw new IllegalStateException
}
}
}
def requireState1Impl(c: blackbox.Context)(cond: c.Expr[Boolean], msg: c.Expr[Any]): c.Expr[Unit] = {
import c.universe._
reify {
if (!cond.splice) {
throw new IllegalStateException(msg.splice.toString)
}
}
}
}
}
示例6: Macros
//设置package包名称以及导入依赖的类
package com.outr.uberterm
import scala.annotation.compileTimeOnly
import scala.reflect.macros.blackbox
@compileTimeOnly("Enable Macros for expansion")
object Macros {
def module[M <: UberTermModule](context: blackbox.Context)
(implicit m: context.WeakTypeTag[M]): context.Expr[M] = {
import context.universe._
val typeString = m.tpe.toString
val (preType, postType) = if (typeString.indexOf('.') != -1) {
val index = typeString.lastIndexOf('.')
typeString.substring(0, index + 1) -> typeString.substring(index + 1)
} else {
"" -> typeString
}
val clientTypeString = s"${preType}Client$postType"
val serverTypeString = s"${preType}Server$postType"
val clientType = try {
Some(context.universe.rootMirror.staticClass(clientTypeString))
} catch {
case _: ScalaReflectionException => None
}
val serverType = try {
Some(context.universe.rootMirror.staticClass(serverTypeString))
} catch {
case exc: ScalaReflectionException => None
}
val communicationType = serverType match {
case Some(t) => t
case None => clientType match {
case Some(t) => t
case None => context.abort(context.enclosingPosition, s"Unable to find implementation trait $clientTypeString or $serverTypeString for $typeString.")
}
}
val application = context.prefix.tree
context.Expr[M](
q"""
val module = new $m()
module.init()
module
""")
}
def help(context: blackbox.Context)(): context.Expr[ModuleHelp] = {
import context.universe._
val test = context.prefix.tree
scribe.info(s"Module: ${test.tpe.members}")
// module.symbol
context.abort(context.enclosingPosition, "WIP")
}
}
示例7: get
//设置package包名称以及导入依赖的类
package csw.services.logging.macros
import scala.language.experimental.macros
import scala.reflect.macros.blackbox
trait SourceFactory {
def get(): SourceLocation
}
object SourceFactory {
implicit def factory: SourceFactory = macro sourceLocationMacro
def from(f: () ? SourceLocation): SourceFactory = () => f()
def from(cls: Class[_]): SourceFactory = from(() ? SourceLocation("", "", cls.getName, -1))
def sourceLocationMacro(c: blackbox.Context): c.Expr[SourceFactory] = {
import c.universe._
val p = c.macroApplication.pos
val file = p.source.file.name
val line = p.line
def allOwners(s: c.Symbol): Seq[c.Symbol] =
if (s == `NoSymbol`) {
Seq()
} else {
s +: allOwners(s.owner)
}
val owners = allOwners(c.internal.enclosingOwner)
val className = owners
.filter(s => s.toString.startsWith("class") || s.toString.startsWith("object"))
.map(s => s.asClass.name.toString)
.reverse
.mkString("$")
val packageName = owners
.filter(_.isPackage)
.map(_.name.toString())
.filter(_ != "<root>")
.reverse
.mkString(".")
c.Expr[SourceFactory](
q"csw.services.logging.macros.SourceFactory.from(() => csw.services.logging.macros.SourceLocation($file,$packageName,$className,$line))"
)
}
}
示例8: Util
//设置package包名称以及导入依赖的类
package com.github.andyglow.relaxed
import scala.language.experimental.macros
import scala.language.postfixOps
import scala.reflect.macros.blackbox
private[relaxed] object Util {
def fieldMap[T]: Map[String, Class[_]] = macro fieldMapImpl[T]
def fieldMapImpl[T: c.WeakTypeTag](c: blackbox.Context): c.Expr[Map[String, Class[_]]] = {
import c.universe._
val tpe = weakTypeOf[T]
val fields = Util.fieldMap(c)(tpe) map { case (n, t) =>
val name = n.decodedName.toString
val tpe = TypeName(t.typeSymbol.name.decodedName.toString)
q"$name -> classOf[$tpe]"
}
val code = q"Map( ..$fields )"
c.Expr[Map[String, Class[_]]](code)
}
def fieldMap(c: blackbox.Context)(tpe: c.universe.Type): Seq[(c.universe.TermName, c.universe.Type)] = {
import c.universe._
val annotations = tpe.decls.collect {
case s: MethodSymbol if s.isCaseAccessor =>
// workaround: force loading annotations
s.typeSignature
s.accessed.annotations.foreach(_.tree.tpe)
s.name.toString.trim -> s.accessed.annotations
}.toMap
def shouldSkip(name: String): Boolean = {
val fieldAnnotations = annotations.getOrElse(name, List.empty)
fieldAnnotations.exists(_.tree.tpe <:< typeOf[skip])
}
object UpdatableField {
def unapply(s: TermSymbol): Option[(TermName, Type)] = {
val name = s.name.toString.trim
if ( s.isVal
&& s.isCaseAccessor
&& !shouldSkip(name)) Some((TermName(name), s.typeSignature)) else None
}
}
tpe.decls.collect {case UpdatableField(n, t) => (n, t)} toSeq
}
}
示例9: MacroUtil
//设置package包名称以及导入依赖的类
package com.evolutiongaming.json
import scala.language.experimental.macros
import scala.language.postfixOps
import scala.reflect.macros.blackbox
private[json] object MacroUtil {
def fieldMap[T]: Map[String, Class[_]] = macro fieldMapImpl[T]
def fieldMapImpl[T: c.WeakTypeTag](c: blackbox.Context): c.Expr[Map[String, Class[_]]] = {
import c.universe._
val tpe = weakTypeOf[T]
val fields = MacroUtil.fieldMap(c)(tpe) map { case (n, t) =>
val name = n.decodedName.toString
val tpe = TypeName(t.typeSymbol.name.decodedName.toString)
q"$name -> classOf[$tpe]"
}
val code = q"Map( ..$fields )"
c.Expr[Map[String, Class[_]]](code)
}
def fieldMap(c: blackbox.Context)(tpe: c.universe.Type): Seq[(c.universe.TermName, c.universe.Type)] = {
import c.universe._
val annotations = tpe.decls.collect {
case s: MethodSymbol if s.isCaseAccessor =>
// workaround: force loading annotations
s.typeSignature
s.accessed.annotations.foreach(_.tree.tpe)
s.name.toString.trim -> s.accessed.annotations
}.toMap
def shouldSkip(name: String): Boolean = {
val fieldAnnotations = annotations.getOrElse(name, List.empty)
fieldAnnotations.exists(_.tree.tpe <:< typeOf[skip])
}
object UpdatableField {
def unapply(s: TermSymbol): Option[(TermName, Type)] = {
val name = s.name.toString.trim
if ( s.isVal
&& s.isCaseAccessor
&& !shouldSkip(name)) Some((TermName(name), s.typeSignature)) else None
}
}
tpe.decls.collect {case UpdatableField(n, t) => (n, t)} toSeq
}
}
示例10: Showable
//设置package包名称以及导入依赖的类
package com.github.cuzfrog.macros.implicittest
import scala.language.experimental.macros
import scala.reflect.macros.blackbox
trait Showable[T] {def show(x: T): String}
private object Showable {
implicit def materializeShowable[T]: Showable[T] = macro provideInstance[T]
def provideInstance[T: c.WeakTypeTag](c: blackbox.Context): c.universe.Tree = {
import c.universe._
val tpe=c.weakTypeOf[T]
q"""
new Showable[$tpe]{
def show(x:$tpe)=x.toString
}
"""
}
}
示例11: FunctionWrapper
//设置package包名称以及导入依赖的类
package com.github.cuzfrog.macros.codegen
import scala.language.experimental.macros
import scala.reflect.macros.blackbox
object FunctionWrapper {
def apply[P, R](fn: P => R): Function[P, R] = macro FunctionMacroImpl.apply_impl[P, R]
}
private object FunctionMacroImpl{
def apply_impl[P, R](c: blackbox.Context)(fn: c.Expr[P => R]): c.Tree = {
import c.universe._
val tree=q"$fn"
println(show(tree))
println(showCode(tree))
tree
}
}
示例12: SourceCode
//设置package包名称以及导入依赖的类
package com.github.cuzfrog.macros.codegen
import scala.language.experimental.macros
import scala.reflect.macros.blackbox
object SourceCode {
def apply[P, R](fn: P => R): String = macro SourceCodeMacroImpl.apply_impl[P, R]
}
private object SourceCodeMacroImpl{
def apply_impl[P, R](c: blackbox.Context)(fn: c.Expr[P => R]): c.Tree = {
import c.universe._
val tree=q"$fn"
println(s"Compilation:$tree")
q"${showCode(tree)}"
//showCode get the source code and quasiqoute lift the string to tree as return
}
}
示例13: toProtobuf
//设置package包名称以及导入依赖的类
package com.joprice.protobuf
import com.google.protobuf.GeneratedMessage
import scala.reflect.macros.blackbox
import scala.language.experimental.macros
import scala.collection.JavaConverters._
trait ToProtobuf[T] {
type Out <: GeneratedMessage
def toProtobuf(t: T): Out
}
object ToProtobuf {
def apply[T](t: T)(implicit tp: ToProtobuf[T]): tp.Out = tp.toProtobuf(t)
implicit def genToProtobuf[T]: ToProtobuf[T] = macro genToProtobufImpl[T]
def genToProtobufImpl[T: c.WeakTypeTag](c: blackbox.Context): c.Expr[ToProtobuf[T]] = {
import c.universe._
val caseClassType = weakTypeOf[T]
val messageClass = MacroHelpers.getMessageClass[T](c)
val messageDescriptor = MacroHelpers.descriptor(c)(messageClass)
val setters = messageDescriptor.getFields.asScala.map { field =>
val name = field.getName
val caseClassField = q"t.${TermName(name)}"
val setter = TermName(s"set${name.capitalize}")
if (field.isOptional)
q"$caseClassField.foreach(b.$setter(_))"
else
//TODO: parameterize prefix 'b'
q"b.$setter($caseClassField)"
}
//println(show(setters))
val tree = q"""
new _root_.com.joprice.protobuf.ToProtobuf[$caseClassType] {
type Out = $messageClass
def toProtobuf(t: $caseClassType): Out = {
val b = ${messageClass.companion}.newBuilder
..$setters
b.build
}
}
"""
c.Expr[ToProtobuf[T]](tree)
}
}
示例14: fromProtobuf
//设置package包名称以及导入依赖的类
package com.joprice.protobuf
import com.google.protobuf.GeneratedMessage
import scala.reflect.macros.blackbox
import scala.language.experimental.macros
import scala.collection.JavaConverters._
trait FromProtobuf[T] {
type Out <: GeneratedMessage
def fromProtobuf(data: Array[Byte]): T
}
object FromProtobuf {
def apply[T](t: Array[Byte])(implicit tp: FromProtobuf[T]): T = tp.fromProtobuf(t)
implicit def genFromProtobuf[T]: FromProtobuf[T] = macro genFromProtobufImpl[T]
def genFromProtobufImpl[T: c.WeakTypeTag](c: blackbox.Context): c.Expr[FromProtobuf[T]] = {
import c.universe._
val messageClass = MacroHelpers.getMessageClass[T](c)
val messageDescriptor = MacroHelpers.descriptor(c)(messageClass)
val getters = messageDescriptor.getFields.asScala.map { field =>
val name = field.getName
val select = q"message.${TermName(s"get${name.capitalize}")}"
val wrapped = if (field.isOptional) {
q"(if (message.${TermName(s"has${name.capitalize}")}) Option($select) else None)"
} else select
q"${TermName(name)} = $wrapped"
}
val caseClassType = weakTypeOf[T]
val tree = q"""
new _root_.com.joprice.protobuf.FromProtobuf[$caseClassType] {
type Out = $messageClass
def fromProtobuf(data: Array[Byte]): $caseClassType = {
val message = ${messageClass.companion}.parseFrom(data)
new $caseClassType(..$getters)
}
}
"""
// println(show(tree))
c.Expr[FromProtobuf[T]](tree)
}
}
示例15: MacroHelpers
//设置package包名称以及导入依赖的类
package com.joprice.protobuf
import com.google.protobuf.Descriptors.Descriptor
import scala.language.experimental.macros
import scala.reflect.macros.blackbox
private[protobuf] object MacroHelpers {
def descriptor(c: blackbox.Context)(messageClass: c.Type) = {
import c.universe._
c.eval(c.Expr[Descriptor](q"${messageClass.companion}.getDescriptor()"))
}
def getMessageClass[T: c.WeakTypeTag](c: blackbox.Context): c.Type = {
import c.universe._
val wt = weakTypeOf[T]
val annotation = wt.typeSymbol.asType.annotations
.find(_.tree.tpe <:< weakTypeOf[protoClass[_]]).getOrElse {
c.abort(c.enclosingPosition,
s"""|Did not find @protoClass annotation on $wt. Add the annotation with the protobuf message type,
|or use @proto annotation to generate the class from the protobuf message class.
|""".stripMargin
)
}
annotation.tree.tpe.typeArgs.head
}
def replaceAnnotatedClass(c: blackbox.Context)(annottees: Seq[c.Expr[Any]])(transform: c.universe.ClassDef => List[c.universe.Tree]) = {
import c.universe._
val members = annottees.map(_.tree).toList match {
case (clazz: ClassDef) :: companion :: Nil =>
transform(clazz) ++ List(companion)
case (clazz: ClassDef) :: Nil =>
transform(clazz)
case _ =>
c.abort(c.enclosingPosition, "Expected annotation to be used on a class")
}
c.Expr[Any](Block(members, Literal(Constant(()))))
}
}