• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala blackbox类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中scala.reflect.macros.blackbox的典型用法代码示例。如果您正苦于以下问题:Scala blackbox类的具体用法?Scala blackbox怎么用?Scala blackbox使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了blackbox类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)} """)
  }


} 
开发者ID:dgouyette,项目名称:git-info,代码行数:55,代码来源:GitInfo.scala


示例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")
    }
  }
} 
开发者ID:outr,项目名称:scarango,代码行数:19,代码来源:CoreMacros.scala


示例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
} 
开发者ID:davegurnell,项目名称:checklist,代码行数:53,代码来源:RuleMacros.scala


示例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)."))
  }
} 
开发者ID:outr,项目名称:iconsole,代码行数:58,代码来源:ProcessorGenerator.scala


示例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)
        }
      }
    }
  }
} 
开发者ID:sirthias,项目名称:swave,代码行数:54,代码来源:Macros.scala


示例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")
  }
} 
开发者ID:outr,项目名称:uberterm,代码行数:61,代码来源:Macros.scala


示例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))"
    )
  }
} 
开发者ID:tmtsoftware,项目名称:csw-prod,代码行数:49,代码来源:SourceFactory.scala


示例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
  }
} 
开发者ID:andyglow,项目名称:relaxed-json-update,代码行数:51,代码来源:Util.scala


示例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
  }
} 
开发者ID:evolution-gaming,项目名称:json-partial-update,代码行数:52,代码来源:MacroUtil.scala


示例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
       }
     """
  }
} 
开发者ID:cuzfrog,项目名称:macros,代码行数:21,代码来源:Showable.scala


示例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
  }
}


 
开发者ID:cuzfrog,项目名称:macros,代码行数:20,代码来源:FunctionWrapper.scala


示例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
  }
} 
开发者ID:cuzfrog,项目名称:macros,代码行数:20,代码来源:SourceCode.scala


示例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)
  }

} 
开发者ID:joprice,项目名称:protogen,代码行数:52,代码来源:ToProtobuf.scala


示例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)
  }

} 
开发者ID:joprice,项目名称:protogen,代码行数:50,代码来源:FromProtobuf.scala


示例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(()))))
  }

} 
开发者ID:joprice,项目名称:protogen,代码行数:43,代码来源:MacroHelpers.scala


示例16: AkkaStreamTestKitSpecificationLike

//设置package包名称以及导入依赖的类
package drt.chroma

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.testkit.TestSubscriber.Probe
import akka.testkit.TestKit
import com.typesafe.config.ConfigFactory
import org.specs2.execute.Result
import org.specs2.mutable.SpecificationLike

import scala.reflect.macros.blackbox

abstract class AkkaStreamTestKitSpecificationLike extends
  TestKit(ActorSystem("AkkaStreamTestKitSpecificationLike", ConfigFactory.empty())) with SpecificationLike {
  implicit val materializer = ActorMaterializer()

  implicit def probe2Success[R <: Probe[_]](r: R): Result = success

  //  implicit def probe2MatchResult[R](r: R): MatchResult[Any] = ok
}

object MatcherHelper {
  def matcherhelper(c: blackbox.Context)(r: c.Tree) = {
    c.error(c.enclosingPosition, "test should finish with a Matcher or a Probe[T]")
    c.abort(c.enclosingPosition, "blah")
  }
} 
开发者ID:UKHomeOffice,项目名称:drt-scalajs-spa-exploration,代码行数:28,代码来源:AkkaStreamTestKitSpecificationLike.scala


示例17: SealedEnum

//设置package包名称以及导入依赖的类
package iliad

import scala.languageFeature.experimental.macros
import scala.reflect.macros.blackbox


object SealedEnum {
  def values[A]: Set[A] = macro SealedEnumMacro.values_impl[A]
}

final class SealedEnumMacro(val c: blackbox.Context) {
  import c.universe._
  def values_impl[A: c.WeakTypeTag]: Tree = {
    val t = symbolOf[A]
    if (!(t.isClass && t.asClass.isSealed)) {
      c.abort(
          c.enclosingPosition,
          "cannot get values of types which are not sealed and a class/trait")
    }
    val cses = t.asClass.knownDirectSubclasses.toList
    if (!cses.forall(_.isModuleClass)) {
      c.abort(c.enclosingPosition,
              "cannot get values of types which have non-object members")
    }
    val all = cses.map(sym => q"""${Ident(sym.name.toTermName)}""")
    q"""Set[$t](..$all)"""
  }
} 
开发者ID:to-ithaca,项目名称:iliad,代码行数:29,代码来源:sealedEnum.scala


示例18: ProtoOpsMacros

//设置package包名称以及导入依赖的类
package deaktator.pops.msgs

import java.io.InputStream

import com.google.protobuf.Descriptors.Descriptor
import com.google.protobuf.{ByteString, CodedInputStream, ExtensionRegistryLite, GeneratedMessage}

import scala.reflect.macros.blackbox


@macrocompat.bundle
class ProtoOpsMacros(val c: blackbox.Context) {
  def materialize[A <: GeneratedMessage: c.WeakTypeTag]: c.Expr[ProtoOps[A]] = {
    import c.universe._

    val a = weakTypeOf[A]
    val protoOps = weakTypeOf[ProtoOps[A]]
    val serializable = weakTypeOf[Serializable]
    val proto = a.companion

    val descriptor = weakTypeOf[Descriptor]
    val byteString = weakTypeOf[ByteString]
    val extensionRegistryLite = weakTypeOf[ExtensionRegistryLite]
    val codedInputStream = weakTypeOf[CodedInputStream]
    val inputStream = weakTypeOf[InputStream]

    c.Expr[ProtoOps[A]] {
      q"""new $protoOps with $serializable {
            def getDefaultInstance(): $a = $proto.getDefaultInstance()
            def getDescriptor(): $descriptor = $proto.getDescriptor()
            def parseFrom(data: $byteString): $a = $proto.parseFrom(data)
            def parseFrom(data: $byteString, extensionRegistry: $extensionRegistryLite): $a =
              $proto.parseFrom(data, extensionRegistry)
            def parseFrom(data: Array[Byte]): $a = $proto.parseFrom(data)
            def parseFrom(data: Array[Byte], extensionRegistry: $extensionRegistryLite): $a =
              $proto.parseFrom(data, extensionRegistry)
            def parseFrom(input: $inputStream): $a = $proto.parseFrom(input)
            def parseFrom(input: $inputStream, extensionRegistry: $extensionRegistryLite): $a =
              $proto.parseFrom(input, extensionRegistry)
            def parseFrom(input: $codedInputStream): $a = $proto.parseFrom(input)
            def parseFrom(input: $codedInputStream, extensionRegistry: $extensionRegistryLite): $a =
              $proto.parseFrom(input, extensionRegistry)
            def parseDelimitedFrom(input: $inputStream): $a = $proto.parseDelimitedFrom(input)
            def parseDelimitedFrom(input: $inputStream, extensionRegistry: $extensionRegistryLite):
              $a = $proto.parseDelimitedFrom(input, extensionRegistry)
          }
       """
    }
  }
} 
开发者ID:deaktator,项目名称:pops,代码行数:51,代码来源:ProtoOpsMacros.scala


示例19: EnumProtoOpsMacros

//设置package包名称以及导入依赖的类
package deaktator.pops.enums

import com.google.protobuf.Descriptors.{EnumDescriptor, EnumValueDescriptor}
import com.google.protobuf.Internal.EnumLiteMap
import com.google.protobuf.ProtocolMessageEnum

import scala.reflect.macros.blackbox


@macrocompat.bundle
class EnumProtoOpsMacros(val c: blackbox.Context) {
  def materialize[A <: ProtocolMessageEnum : c.WeakTypeTag]: c.Expr[EnumProtoOps[A]] = {
    import c.universe._

    val enumProtoOps = weakTypeOf[EnumProtoOps[A]]
    val a = weakTypeOf[A]
    val enm = a.companion
    val enumDescriptor = weakTypeOf[EnumDescriptor]
    val enumValueDescriptor = weakTypeOf[EnumValueDescriptor]
    val enumLiteMap = weakTypeOf[EnumLiteMap[A]]
    val serializable = weakTypeOf[Serializable]

    c.Expr[EnumProtoOps[A]] {
      q"""new $enumProtoOps with $serializable {
            def getDescriptor(): $enumDescriptor = $enm.getDescriptor()
            def internalGetValueMap(): $enumLiteMap = $enm.internalGetValueMap()
            def valueOf(value: Int): $a = $enm.valueOf(value)
            def valueOf(desc: $enumValueDescriptor): $a = $enm.valueOf(desc)
          }
       """
    }
  }
} 
开发者ID:deaktator,项目名称:pops,代码行数:34,代码来源:EnumProtoOpsMacros.scala


示例20: createJsonAstImpl

//设置package包名称以及导入依赖的类
package net.scholtzan.macba.json.auto

import org.json4s.JsonAST.JValue
import scala.language.experimental.macros
import scala.reflect.macros.blackbox


  def createJsonAstImpl[T](c: blackbox.Context)(obj: c.Expr[T]): c.Tree = {
    import c.universe._

    // determine the type and its corresponding JSON AST value
    obj match {
      case x if x.actualType <:< typeOf[Int] =>
        q"org.json4s.JsonAST.JInt($x)"

      case x if x.actualType.typeSymbol == typeOf[Double].typeSymbol =>
        q"org.json4s.JsonAST.JDouble($x)"

      case x if x.actualType.typeSymbol == typeOf[BigDecimal].typeSymbol =>
        q"org.json4s.JsonAST.JDecimal($x)"

      case x if x.actualType.typeSymbol == typeOf[Long].typeSymbol =>
        q"org.json4s.JsonAST.JLong($x)"

      case x if x.actualType.typeSymbol == typeOf[String].typeSymbol =>
        q"org.json4s.JsonAST.JString($x)"

      case x if x.actualType.typeSymbol == typeOf[Boolean].typeSymbol =>
        q"org.json4s.JsonAST.JBool($x)"

      case x if x.actualType <:< typeOf[Null] =>
        q"org.json4s.JsonAST.JNull"

      case x if x.actualType <:< typeOf[Seq[Any]]  =>
        q"org.json4s.JsonAST.JArray($obj.map(createJsonAst(_)).toList)"

      case x if x.actualType <:< typeOf[List[Any]] =>
        q"org.json4s.JsonAST.JArray($obj.map(createJsonAst(_)))"

      case x =>  // unknown object or data type

        // get all members and methods
        val methods: Iterable[c.Symbol] = obj.tree.tpe.decls

        // get accessible values and variables only
        val fields = methods.filter(sym => sym.isMethod && sym.asMethod.isAccessor)

        // create the JSON AST by recursively generating key value pairs
        val jsonObjectAst = q"""
          org.json4s.JsonAST.JObject(List(..${fields.map { field =>
            q"""org.json4s.JsonAST.JField(${field.name.toString}, createJsonAst($obj.${field.name.toTermName}))"""
          }}))
        """

        jsonObjectAst
    }
  }
} 
开发者ID:scholtzan,项目名称:macba-json,代码行数:59,代码来源:JsonAstGenerator.scala



注:本文中的scala.reflect.macros.blackbox类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala Response类代码示例发布时间:2022-05-23
下一篇:
Scala ConfigurationBuilder类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap