本文整理汇总了Scala中scala.reflect.macros.blackbox.Context类的典型用法代码示例。如果您正苦于以下问题:Scala Context类的具体用法?Scala Context怎么用?Scala Context使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Context类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: MacroImpl
//设置package包名称以及导入依赖的类
package underscoreio
package holes
import scala.reflect.macros.blackbox.Context
object MacroImpl {
def hole(c: Context): c.Tree = {
import c.universe._
val targetType: Option[c.universe.Type] = {
c.internal.enclosingOwner match {
case ts: TermSymbol =>
println(s"Symbol: $ts, signature: ${ts.typeSignature}")
Some(ts.typeSignature.finalResultType)
case o =>
c.error(c.enclosingPosition, "Hole macro impcomplete: doesn't know what to do with {o.getClass}")
None
}
}
targetType match {
case Some(t) => c.error(c.enclosingPosition, s"Hole found which needs to be filled with type: ${t}")
case None => c.error(c.enclosingPosition, "Hole exists, but type to fill cannot be determined")
}
q"???"
}
}
开发者ID:d6y,项目名称:holes,代码行数:31,代码来源:macro.scala
示例2: DebugMacros
//设置package包名称以及导入依赖的类
package com.bob.scalatour.macros
import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Context
object DebugMacros {
def debugm(params: Any*): Unit = macro debugm_impl
def debugm_impl(c: Context)(params: c.Expr[Any]*): c.Expr[Unit] = {
import c.universe._
val trees = params.map(param => {
param.tree match {
case c.universe.Literal(c.universe.Constant(const)) => {
val reified = reify {
print(param.splice)
}
reified.tree
}
case _ => {
val paramRep = show(param.tree)
val paramRepTree = Literal(Constant(paramRep))
val paramRepExpr = c.Expr[String](paramRepTree)
val reified = reify {
print(paramRepExpr.splice + " = " + param.splice)
}
reified.tree
}
}
})
// Inserting ", " between trees, and a println at the end.
val separators = (1 to trees.size - 1).map(_ => (reify {
print(", ")
}).tree) :+ (reify {
println()
}).tree
val treesWithSeparators = trees.zip(separators).flatMap(p => List(p._1, p._2))
c.Expr[Unit](Block(treesWithSeparators.toList, Literal(Constant(()))))
}
def hello(): Unit = macro hello_impl
def hello_impl(c: Context)(): c.Expr[Unit] = {
import c.universe._
c.Expr[Unit]( q"""println("Hello World")""")
}
}
开发者ID:bobxwang,项目名称:scalatour,代码行数:49,代码来源:DebugMacros.scala
示例3: FillDefs
//设置package包名称以及导入依赖的类
package me.yzhi.scala.macros
import scala.annotation.StaticAnnotation
import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Context
class FillDefs extends StaticAnnotation {
def macroTransform(annottees: Any*) = macro ImplMacros.addDefs
}
object ImplMacros {
def addDefs(c: Context)(annottees: c.Expr[Any]*) = {
impl(c)(false, annottees: _*)
}
def impl(c: Context)(addSuper: Boolean, annottees: c.Expr[Any]*): c.Expr[Any] = {
import c.universe._
val inputs = annottees.map(_.tree).toList
// create the definitions we're going to add
val newDefDefs = List(
DefDef(Modifiers(), TermName("x"), List(), List(), TypeTree(), Literal(Constant(5))),
DefDef(Modifiers(), TermName("y"), List(), List(), TypeTree(), Literal(Constant(7.0f))),
DefDef(Modifiers(), TermName("f"), List(), List(List(ValDef(Modifiers(),
TermName("a"), Ident(TypeName("Int")), EmptyTree))), TypeTree(),
Apply(Select(Ident(TermName("a")), TermName("$plus")), List(Literal(Constant(3))))),
DefDef(Modifiers(), TermName("f2"), List(), List(List(ValDef(Modifiers(),
TermName("a"), Ident(TypeName("Int")), EmptyTree))), TypeTree(),
Apply(Select(Ident(TermName("a")), TermName("$plus")), List(Ident(TermName("b")))))
)
// pattern match on the inputs
val modDefs = inputs map { tree => tree match {
case ClassDef(mods, name, something, template) =>
println(s"DEBUG: $mods | $name | $something | $template")
val q = template match {
case Template(superMaybe, emptyValDef, defs) =>
Template(superMaybe, emptyValDef, defs ++ newDefDefs)
case ex =>
throw new IllegalArgumentException(s"Invalid template: $ex")
}
ClassDef(mods, name, something, q)
case ModuleDef(mods, name, template) =>
println(s"DEBUG Module: $mods | $name | $template")
val q = template match {
case Template(superMaybe, emptyValDef, defs) =>
println(s"DEBUG Template: $superMaybe | $emptyValDef | $defs")
Template(superMaybe, emptyValDef, defs ++ newDefDefs)
case ex =>
throw new IllegalArgumentException(s"Invalid template: $ex")
}
ModuleDef(mods, name, q)
case ex =>
throw new IllegalArgumentException(s"Invalid macro input: $ex")
}
}
// wrap the result up in an Expr, and return it
val result = c.Expr(Block(modDefs, Literal(Constant())))
result
}
}
开发者ID:javelinjs,项目名称:scala-macro-learning,代码行数:62,代码来源:ImplMacros.scala
示例4: derivePath
//设置package包名称以及导入依赖的类
package wiro
import scala.reflect.macros.blackbox.Context
import scala.language.experimental.macros
import wiro.annotation.path
trait PathMacro {
def derivePath[A]: String = macro PathMacro.derivePathImpl[A]
}
object PathMacro extends PathMacro {
def derivePathImpl[A: c.WeakTypeTag](c: Context): c.Tree = {
import c.universe._
val tpe = weakTypeOf[A].typeSymbol
tpe.annotations.collectFirst {
case pathAnnotation if pathAnnotation.tree.tpe <:< c.weakTypeOf[path] =>
pathAnnotation.tree.children.tail.head
}.getOrElse {
c.abort(c.enclosingPosition, s"\n\nMissing annotation @path(<name>) on $tpe\n")
}
}
}
开发者ID:buildo,项目名称:wiro,代码行数:27,代码来源:PathMacro.scala
示例5: typePath
//设置package包名称以及导入依赖的类
package wiro
import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Context
import wiro.annotation.path
trait TypePathMacro {
def typePath[A]: Seq[String] = macro TypePathMacro.typePathImpl[A]
}
object TypePathMacro extends TypePathMacro {
def typePathImpl[A: c.WeakTypeTag](c: Context): c.Tree = {
import c.universe._
val tpe = weakTypeOf[A].typeSymbol
val path = tpe.fullName.toString.split('.').toSeq
q"Seq(..$path)"
}
}
开发者ID:buildo,项目名称:wiro,代码行数:22,代码来源:TypePathMacro.scala
示例6: name
//设置package包名称以及导入依赖的类
package wiro
import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Context
import wiro.annotation._
sealed trait OperationType {
def name: Option[String]
}
object OperationType {
case class Command(name: Option[String]) extends OperationType
case class Query(name: Option[String]) extends OperationType
}
case class MethodMetaData(
operationType: OperationType
)
trait MetaDataMacro {
def deriveMetaData[A]: Map[String, MethodMetaData] = macro MetaDataMacro.deriveMetaDataImpl[A]
}
object MetaDataMacro extends MetaDataMacro {
def deriveMetaDataImpl[A: c.WeakTypeTag](c: Context): c.Tree = {
import c.universe._
val decls = weakTypeOf[A].decls.collect {
case m: MethodSymbol =>
val methodName = m.fullName
val operationType = m.annotations.collectFirst {
case opAnnotation if opAnnotation.tree.tpe <:< c.weakTypeOf[command] =>
val name = opAnnotation.tree.children.tail.head
q"OperationType.Command($name)"
case opAnnotation if opAnnotation.tree.tpe <:< c.weakTypeOf[query] =>
val name = opAnnotation.tree.children.tail.head
q"OperationType.Query($name)"
}
q"($methodName -> $operationType.map { o => MethodMetaData(o) })"
}
q"Map(..$decls) collect { case (k, Some(v)) => (k -> v) }"
}
}
开发者ID:buildo,项目名称:wiro,代码行数:47,代码来源:MetaDataMacro.scala
示例7: deriveRouter
//设置package包名称以及导入依赖的类
package wiro
package server.akkaHttp
import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Context
import wiro.annotation.path
trait RouterDerivationModule extends PathMacro with MetaDataMacro with TypePathMacro {
def deriveRouter[A](a: A): Router = macro RouterDerivationMacro.deriveRouterImpl[A]
}
object RouterDerivationMacro extends RouterDerivationModule {
def deriveRouterImpl[A: c.WeakTypeTag](c: Context)(a: c.Expr[A]): c.Tree = {
import c.universe._
val tpe = weakTypeOf[A]
//check only annotations of path type
val pathAnnotated = tpe.typeSymbol.annotations.collectFirst {
case pathAnnotation if pathAnnotation.tree.tpe <:< c.weakTypeOf[path] => pathAnnotation
}
val derivePath = pathAnnotated match {
case None => EmptyTree
case _ => q"override val path = derivePath[$tpe]"
}
q"""
import wiro.{ OperationType, MethodMetaData }
new Router {
override val routes = route[$tpe]($a)
override val methodsMetaData = deriveMetaData[$tpe]
override val tp = typePath[$tpe]
$derivePath
}
"""
}
}
开发者ID:buildo,项目名称:wiro,代码行数:40,代码来源:RouterDerivation.scala
示例8: deriveClientContext
//设置package包名称以及导入依赖的类
package wiro
package client.akkaHttp
import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Context
trait ClientDerivationModule extends TypePathMacro {
def deriveClientContext[A]: RPCClientContext[A] = macro ClientDerivationMacro.deriveClientContextImpl[A]
}
object ClientDerivationMacro extends ClientDerivationModule {
def deriveClientContextImpl[A: c.WeakTypeTag](c: Context): c.Tree = {
import c.universe._
val tpe = weakTypeOf[A]
q"""
import wiro.{ OperationType, MethodMetaData }
new RPCClientContext[$tpe] {
override val methodsMetaData = deriveMetaData[$tpe]
override val tp = typePath[$tpe]
override val path = derivePath[$tpe]
}
"""
}
}
开发者ID:buildo,项目名称:wiro,代码行数:27,代码来源:ClientDerivation.scala
示例9: Reader
//设置package包名称以及导入依赖的类
package parsec.optimised
import scala.reflect.macros.blackbox.Context
import util.Zeroval
trait ReaderOps {
val c: Context
import c.universe._
abstract class Reader(elemType: Type) {
def first: Tree
def atEnd: Tree
def rest: Reader
}
abstract class CharReader extends Reader(typeOf[Char]) { self =>
def apply(cont: (Tree, Tree) => Tree): Tree
def first = self.apply((source, pos) => q"$source($pos)")
def atEnd = self.apply((source, pos) => q"$pos >= $source.length")
def rest = new CharReader {
def apply(cont: (Tree, Tree) => Tree) =
self.apply((source, pos) => cont(source, q"$pos + 1"))
}
def getSource = self.apply((src, _) => src)
def getPos = self.apply((_, p) => p)
def toCharReader: Tree = self.apply {
//(source, pos) => q"CharReader(${source.symbol}, ${pos.symbol})"
(source, pos) => q"CharReader($source, $pos)"
}
}
def mkCharReader(source: Tree, pos: Tree) = new CharReader {
def apply(cont: (Tree, Tree) => Tree) = cont(source, pos)
}
def cond(test: Tree, thenp: CharReader, elsep: CharReader) = {
new CharReader {
def apply(cont: (Tree, Tree) => Tree) = {
q"""
if ($test) ${thenp(cont)}
else ${elsep(cont)}
"""
}
}
}
}
开发者ID:manojo,项目名称:parsequery,代码行数:53,代码来源:CharReaderOps.scala
示例10: zeroValue
//设置package包名称以及导入依赖的类
package parsec.optimised.util
import scala.reflect.macros.blackbox.Context
trait Zeroval {
val c: Context
import c.universe._
//scalastyle:off line.size.limit
//scalastyle:on line.size.limit
def zeroValue(typ: Type): Tree = {
if (typ =:= typeOf[scala.Char]) q"0"
else if (typ =:= typeOf[scala.Int]) q"0"
else if (typ =:= typeOf[scala.Unit]) q"()"
else if (typ =:= typeOf[scala.Double]) q"0.0"
else q"null"
}
}
开发者ID:manojo,项目名称:parsequery,代码行数:22,代码来源:Zeroval.scala
示例11: OrigOwnerAttachment
//设置package包名称以及导入依赖的类
package macroutil {
import scala.reflect.macros.blackbox.Context
case class OrigOwnerAttachment(sym: Any)
object Splicer {
import scala.reflect.macros._
import blackbox.Context
def impl[A](c: Context)(expr: c.Expr[A]): c.Expr[A] = {
val helper = new Splicer[c.type](c)
c.Expr[A](helper.changeOwner(expr.tree))
}
class Splicer[C <: Context](val c: C) {
import c.universe._
import c.universe.definitions._
import c.internal._, decorators._
def changeOwner(tree: c.Tree): c.Tree = {
import c.universe._, internal._, decorators._
val origOwner = tree.attachments.get[OrigOwnerAttachment].map(_.sym).get.asInstanceOf[Symbol]
c.internal.changeOwner(tree, origOwner, c.internal.enclosingOwner)
}
}
def changeOwner[A](expr: A): A = macro impl[A]
}
}
开发者ID:manojo,项目名称:parsequery,代码行数:29,代码来源:macroutil.scala
示例12: PrintVar
//设置package包名称以及导入依赖的类
package simple
import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Context
object PrintVar {
def printVarName[T](variable: T): String = macro printVarNameImpl[T]
def printVarNameImpl[T] (c: Context) (variable: c.Expr[T]) = {
import c.universe._
val varName = variable.tree.symbol.name.decodedName.toString
q"""
$varName
"""
}
def printVar[T](variable: T): String = macro printVarImpl[T]
def printVarImpl[T] (c: Context) (variable: c.Expr[T]) = {
import c.universe._
val varName = variable.tree.symbol.name.decodedName.toString
val value = variable.tree
q"""
$varName + "=\"" + $value.toString + "\""
"""
}
}
开发者ID:gustavoamigo,项目名称:scamacros-samples,代码行数:31,代码来源:PrintVar.scala
示例13: TestTransformer
//设置package包名称以及导入依赖的类
package tryp.test.fixtures
import scala.reflect.macros.blackbox.Context
import annotation.StaticAnnotation
import tryp.Annotation
trait TestAnnotationBase
extends Annotation
{
import c.universe._
object TestTransformer
extends Transformer
{
def apply(annottees: Annottees) = {
annottees
}
}
override def transformers = TestTransformer :: Nil
}
class Test
extends StaticAnnotation
{
def macroTransform(annottees: Any*) = macro TestAnnotation.process
}
class TestAnnotation(val c: Context)
extends TestAnnotationBase
开发者ID:tek,项目名称:pulsar,代码行数:32,代码来源:test.scala
示例14: MacrosImpl
//设置package包名称以及导入依赖的类
package io.bluecabin.common.macros
import scala.annotation.tailrec
import scala.reflect.macros.blackbox.Context
private[macros] object MacrosImpl {
def singletonsImpl[A: c.WeakTypeTag](c: Context): c.Expr[Traversable[A]] = {
import c.universe._
val A = weakTypeOf[A]
val typeSym = A.typeSymbol
val singletonIdents = if ((typeSym.isClass) && (typeSym.asClass.isSealed)) {
@tailrec def topParentInPackage(s: c.universe.Symbol): c.universe.Symbol = {
val owner = s.owner
if (owner.isPackage) owner else if (owner == NoSymbol) s else topParentInPackage(owner)
}
@tailrec def nestedSingletons(inputs: Vector[c.universe.Symbol], currResult: Vector[c.universe.Symbol])
(filter: c.universe.ModuleSymbol => Boolean): Vector[c.universe.Symbol] = {
inputs.headOption match {
case Some(m: ModuleSymbol) =>
val newResult = if (filter(m)) currResult :+ m else currResult
nestedSingletons(m.typeSignature.decls.toVector ++ inputs.tail, newResult)(filter)
case Some(m: ClassSymbol) => nestedSingletons(m.typeSignature.decls.toVector ++ inputs.tail, currResult)(filter)
case Some(s) =>
nestedSingletons(inputs.tail, currResult)(filter)
case None => currResult
}
}
val top = topParentInPackage(c.internal.enclosingOwner)
nestedSingletons(Vector(top), Vector.empty) { m =>
m.typeSignature.baseClasses.contains(typeSym)
} map (Ident(_))
} else {
c.abort(
c.enclosingPosition,
"Only sealed traits or classes are allowed"
)
}
c.Expr[Traversable[A]](q"Traversable(..$singletonIdents)")
}
}
开发者ID:bluecabin,项目名称:common-macros,代码行数:48,代码来源:MacrosImpl.scala
示例15: debug
//设置package包名称以及导入依赖的类
package io.flatmap.ml.macros
import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Context
object debug {
def apply[T](x: => T): T = macro impl
def impl(c: Context)(x: c.Tree) = { import c.universe._
val q"..$stats" = x
val loggedStats = stats.flatMap { stat =>
val msg = "executing " + stat
List(q"println($msg)", stat)
}
q"..$loggedStats"
}
}
开发者ID:ShokuninSan,项目名称:som,代码行数:20,代码来源:debug.scala
示例16: untyped
//设置package包名称以及导入依赖的类
package repos
import java.util.UUID
import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Context
trait IdType extends Any {
def untyped: UUID
}
object IdMapper {
implicit def materializeIdFactory[T <: IdType]: IdMapper[T] = macro materializeIdFactoryImpl[T]
def materializeIdFactoryImpl[T: c.WeakTypeTag](c: Context): c.Expr[IdMapper[T]] = {
import c.universe._
val tpe = weakTypeOf[T]
val companion = tpe.typeSymbol.companion
c.Expr[IdMapper[T]] {
q"""
new _root_.repos.IdMapper[$tpe] {
def fromUUID(s: java.util.UUID): $tpe = $companion(s)
def toUUID(t: $tpe): java.util.UUID = t.untyped
}
"""
}
}
private val ZeroUUID: UUID = new UUID(0, 0)
private val IdRegex = "[0-9a-f]{32}".r.pattern
def isValidId(s: String) = s.isEmpty || IdRegex.matcher(s).matches()
}
开发者ID:trueaccord,项目名称:repos,代码行数:37,代码来源:IdMapper.scala
示例17: ShouldNotTypecheck
//设置package包名称以及导入依赖的类
package com.lightbend.lagom.macrotestkit
import scala.language.experimental.macros
import java.util.regex.Pattern
import scala.reflect.macros.TypecheckException
import scala.reflect.macros.blackbox.Context
object ShouldNotTypecheck {
def apply(name: String, code: String): Unit = macro applyImplNoExp
def apply(name: String, code: String, expected: String): Unit = macro applyImpl
def applyImplNoExp(ctx: Context)(name: ctx.Expr[String], code: ctx.Expr[String]) = applyImpl(ctx)(name, code, null)
def applyImpl(ctx: Context)(name: ctx.Expr[String], code: ctx.Expr[String], expected: ctx.Expr[String]): ctx.Expr[Unit] = {
import ctx.universe._
val Expr(Literal(Constant(codeStr: String))) = code
val Expr(Literal(Constant(nameStr: String))) = name
val (expPat, expMsg) = expected match {
case null => (null, "Expected some error.")
case Expr(Literal(Constant(s: String))) =>
(Pattern.compile(s, Pattern.CASE_INSENSITIVE), "Expected error matching: " + s)
}
try ctx.typecheck(ctx.parse("{ " + codeStr + " }")) catch {
case e: TypecheckException =>
val msg = e.getMessage
if ((expected ne null) && !expPat.matcher(msg).matches) {
ctx.abort(ctx.enclosingPosition, s"$nameStr failed in an unexpected way.\n$expMsg\nActual error: $msg")
} else {
println(s"$nameStr passed.")
return reify(())
}
}
ctx.abort(ctx.enclosingPosition, s"$nameStr succeeded unexpectedly.\n$expMsg")
}
}
开发者ID:lagom,项目名称:lagom,代码行数:41,代码来源:ShouldNotTypecheck.scala
示例18: ScaladslServerMacroImpl
//设置package包名称以及导入依赖的类
package com.lightbend.lagom.internal.scaladsl.server
import com.lightbend.lagom.internal.scaladsl.client.ScaladslClientMacroImpl
import com.lightbend.lagom.scaladsl.api.{ Descriptor, Service }
import com.lightbend.lagom.scaladsl.server.{ LagomServer, LagomServiceBinder }
import scala.reflect.macros.blackbox.Context
private[lagom] object ScaladslServerMacroImpl {
def simpleBind[T <: Service](c: Context)(serviceFactory: c.Tree)(implicit serviceType: c.WeakTypeTag[T]): c.Expr[LagomServer] = {
import c.universe._
val scaladsl = q"_root_.com.lightbend.lagom.scaladsl"
val server = q"$scaladsl.server"
val descriptor = readDescriptor[T](c)
c.Expr[LagomServer](q"""{
$server.LagomServer.forService(
$server.LagomServiceBinder(lagomServerBuilder, $descriptor).to($serviceFactory)
)
}
""")
}
def readDescriptor[T <: Service](c: Context)(implicit serviceType: c.WeakTypeTag[T]): c.Expr[Descriptor] = {
import c.universe._
val extracted = ScaladslClientMacroImpl.validateServiceInterface[T](c)
val serviceMethodImpls = (extracted.serviceCalls ++ extracted.topics).map { serviceMethod =>
val methodParams = serviceMethod.paramLists.map { paramList =>
paramList.map(param => q"${param.name.toTermName}: ${param.typeSignature}")
}
q"""
override def ${serviceMethod.name}(...$methodParams) = {
throw new _root_.scala.NotImplementedError("Service methods and topics must not be invoked from service trait")
}
"""
}
c.Expr[Descriptor](q"""
new ${serviceType.tpe} {
..$serviceMethodImpls
}.descriptor
""")
}
}
开发者ID:lagom,项目名称:lagom,代码行数:54,代码来源:ScaladslServerMacroImpl.scala
示例19: DSLFeature
//设置package包名称以及导入依赖的类
package org.scala_lang.virtualized
import scala.reflect.macros.blackbox.Context
import language.experimental.macros
import scala.util.matching.Regex
trait MacroModule {
type Ctx <: Context
val c: Ctx
}
trait DataDefs extends MacroModule {
import c.universe._
case class DSLFeature(tpe: Option[Type], name: String, targs: List[Tree], args: List[List[Type]])
}
def className: String = ???
lazy val typeRegex = new Regex("(" + className.replace("$", "\\$") + """\.this\.)(\w*)""")
lazy val typetagRegex = new Regex("""(scala\.reflect\.runtime\.[a-zA-Z`]*\.universe\.typeTag\[)(\w*)\]""")
def code(tree: Tree, shortenDSLNames: Boolean = true): String = {
var short = showCode(tree)
if (shortenDSLNames) {
typeRegex findAllIn short foreach { m =>
val typeRegex(start, typ) = m
short = short.replace(start + typ, typ.toUpperCase())
}
typetagRegex findAllIn short foreach { m =>
val typetagRegex(start, typ) = m
short = short.replace(start + typ + "]", "TYPETAG[" + typ.toUpperCase() + "]")
}
}
short
}
}
开发者ID:GeorgOfenbeck,项目名称:websiteSpiralS,代码行数:36,代码来源:Utils.scala
示例20: Macros
//设置package包名称以及导入依赖的类
package com.qvantel.jsonapi
import scala.annotation.compileTimeOnly
import scala.reflect.macros.blackbox.Context
import com.qvantel.jsonapi.macrosupport.{JsonApiReaders, JsonApiWriters}
@compileTimeOnly("Macros can only be used at compile-time")
final class Macros(val c: Context) extends JsonApiWriters with JsonApiReaders {
import c.universe._
private[this] def createFormat(t: c.Type): c.Tree = {
val rootParamName = TermName(c.freshName("root"))
val includedParamName = TermName(c.freshName("included"))
val includePaths = TermName(c.freshName("includePaths"))
val includePath = TermName(c.freshName("includePath"))
q"""new _root_.com.qvantel.jsonapi.JsonApiFormat[$t] with _root_.spray.json.RootJsonFormat[$t] {
import _root_.com.qvantel.jsonapi.PathJsonFormat
override final def write($rootParamName: $t): _root_.spray.json.JsValue = ${primaryDataWriter(t,
rootParamName)}
override final def included($rootParamName: $t): _root_.scala.collection.immutable.Set[_root_.spray.json.JsObject] = ${includedWriter(
t,
rootParamName)}
override final def read(
$rootParamName: _root_.spray.json.JsValue,
$includedParamName: _root_.scala.collection.immutable.Map[(String, String), _root_.spray.json.JsObject],
$includePaths: _root_.scala.collection.immutable.Set[String],
$includePath: String
): $t = ${reader(t, rootParamName, includedParamName, includePaths, includePath)}
}"""
}
def createIncludes[A: c.WeakTypeTag]: c.Tree = {
val t = weakTypeOf[A]
val includeParamName = TermName(c.freshName())
val includeMapParamName = TermName(c.freshName())
q"""
new _root_.com.qvantel.jsonapi.Includes[$t] {
private[this] final lazy val $includeMapParamName: Map[String, _root_.com.qvantel.jsonapi.Includes[_]] = ${includesMap(
t)}
override def includeAllowed($includeParamName: String): Boolean = ${includeAllowed(t,
includeParamName,
includeMapParamName)}
}
"""
}
def jsonApiWriterWithNoNameManglingImpl[A: c.WeakTypeTag]: c.Tree = createWriter(weakTypeOf[A])
def jsonApiFormatWithNoNameManglingImpl[A: c.WeakTypeTag]: c.Tree = createFormat(weakTypeOf[A])
}
开发者ID:qvantel,项目名称:jsonapi-scala,代码行数:53,代码来源:Macros.scala
注:本文中的scala.reflect.macros.blackbox.Context类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论