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

Scala StaticAnnotation类代码示例

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

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



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

示例1: 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


示例2: databasefields

//设置package包名称以及导入依赖的类
package wow.common.database

import scalikejdbc.interpolation.SQLSyntax

import scala.annotation.StaticAnnotation
import scala.reflect.macros._

//noinspection SpellCheckingInspection
case class databasefields(s: String*) extends StaticAnnotation


object ExtraFieldsSQLInterpolationMacro {
  def selectDynamic[E: c.WeakTypeTag](c: blackbox.Context)(name: c.Expr[String]): c.Expr[SQLSyntax] = {
    import c.universe._

    def getName(s: c.universe.Symbol) = s.name.encodedName.toString.trim

    val tpe = c.weakTypeOf[E]
    val ctor = tpe.decl(c.universe.termNames.CONSTRUCTOR).asMethod
    // primary constructor args of type E
    val expectedNames = ctor.paramLists.flatMap { symbols: List[Symbol] => symbols.map(getName) }.toBuffer

    def parseAnnotations(symbol: Symbol) = {
      for (annotation <- symbol.annotations if annotation.tree.tpe == typeOf[databasefields]) yield {
        assert(expectedNames contains getName(symbol), s"${getName(symbol)} not present in $expectedNames")

        expectedNames -= getName(symbol)
        expectedNames ++= annotation.tree.children.tail.collect { case Literal(Constant(field: String)) => field }
      }
    }

    ctor.paramLists.flatten.foreach(parseAnnotations)

    name.tree match {
      case Literal(Constant(value: String)) =>
        if (!expectedNames.contains(value)) {
          c.error(c.enclosingPosition,
            s"${c.weakTypeOf[E]}#$value not found. Expected fields are ${expectedNames.mkString("#", ", #", "")}.")
        }
      case _ => None
    }

    c.Expr[SQLSyntax](q"super[SQLSyntaxSupport].column.field($name)")
  }
} 
开发者ID:SKNZ,项目名称:SpinaciCore,代码行数:46,代码来源:ExtraFieldsSQLInterpolationMacro.scala


示例3: Fields

//设置package包名称以及导入依赖的类
package com.scalagen.macros

import scala.annotation.{StaticAnnotation, compileTimeOnly}
import scala.meta._

@compileTimeOnly("@fields not expanded")
class Fields extends StaticAnnotation {
  inline def apply(defn: Any): Any = meta {
    defn match {
      case q"..$mods class SourceContainer (...$paramss) extends $template" =>
          template match {

            case template"{ ..$stats } with ..$ctorcalls { $param => ..$body }" =>

              val newBody = body :+ q"""def fields = this.length """
              val newTemplate = template"{ ..$stats } with ..$ctorcalls { $param => ..$newBody }"

              q"..$mods class SourceContainer (...$paramss) extends $newTemplate"

          }
      case _ => throw new Exception("Thing happened that not work")
    }
  }
} 
开发者ID:hntd187,项目名称:scalagen,代码行数:25,代码来源:Macros.scala


示例4: enableMembersIf

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

import scala.annotation.StaticAnnotation
import scala.reflect.internal.annotations.compileTimeOnly
import scala.reflect.macros.Context

object enableMembersIf {

  private[enableMembersIf] object Macros {
    def macroTransform(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {

      import c.universe._
      def constructors(body: List[Tree]): List[Tree] = {
        (for {
          [email protected](_, nme.CONSTRUCTOR, _, _, _, _) <- body.view
        } yield constructor).take(1).toList
      }

      val Apply(Select(Apply(_, List(condition)), _), List([email protected]_*)) = c.macroApplication
      if (c.eval(c.Expr[Boolean](
        q"""
          _root_.com.thoughtworks.enableIf.isEnabled(${reify(c).tree}, $condition)
        """))) {
        c.Expr(q"..${annottees.map(_.tree)}")
      } else {
        val head = annottees.head.tree match {
          case ClassDef(mods, name, tparams, Template(parents, self, body)) =>
            ClassDef(mods, name, tparams, Template(parents, self, constructors(body)))
          case ModuleDef(mods, name, Template(parents, self, body)) =>
            ModuleDef(mods, name, Template(parents, self, constructors(body)))
        }
        c.Expr(q"$head; ..${annottees.tail}")

      }
    }
  }

}

@compileTimeOnly("enableIf.scala requires macros paradise plugin")
final class enableMembersIf(condition: Context => Boolean) extends StaticAnnotation {

  throw new AssertionError("enableIf.scala requires macro paradise plugin")

  def this(condition: Boolean) = this { _ => condition }

  import scala.language.experimental.macros

  def macroTransform(annottees: Any*): Any = macro enableMembersIf.Macros.macroTransform

} 
开发者ID:ThoughtWorksInc,项目名称:enableIf.scala,代码行数:52,代码来源:enableMembersIf.scala


示例5: enableIf

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

import scala.annotation.StaticAnnotation
import scala.reflect.internal.annotations.compileTimeOnly
import scala.reflect.macros.Context

object enableIf {

  def isEnabled(c: Context, booleanCondition: Boolean) = booleanCondition

  def isEnabled(c: Context, functionCondition: Context => Boolean) = functionCondition(c)

  private[enableIf] object Macros {
    def macroTransform(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
      import c.universe._
      val Apply(Select(Apply(_, List(condition)), _), List([email protected]_*)) = c.macroApplication
      if (c.eval(c.Expr[Boolean](
        q"""
          _root_.com.thoughtworks.enableIf.isEnabled(${reify(c).tree}, $condition)
        """))) {
        c.Expr(q"..${annottees.map(_.tree)}")
      } else {
        c.Expr(EmptyTree)
      }
    }
  }

}

@compileTimeOnly("enableIf.scala requires macros paradise plugin")
final class enableIf(condition: Context => Boolean) extends StaticAnnotation {

  throw new AssertionError("enableIf.scala requires macro paradise plugin")

  def this(condition: Boolean) = this { _ => condition }

  import scala.language.experimental.macros

  def macroTransform(annottees: Any*): Any = macro enableIf.Macros.macroTransform

} 
开发者ID:ThoughtWorksInc,项目名称:enableIf.scala,代码行数:42,代码来源:enableIf.scala


示例6: mappable

//设置package包名称以及导入依赖的类
package scala.meta.serialiser

import scala.annotation.StaticAnnotation
import scala.collection.immutable.Seq
import scala.meta._

class mappable extends StaticAnnotation {
  inline def apply(defn: Any): Any = meta {
    val q"..$mods class $tName (..$params) extends $template" = defn

    val keyValues: Seq[Term] = params.map { param =>
      val memberName = Term.Name(param.name.value)
      q"${param.name.value} -> $memberName"
    }

    val res = q"""
      ..$mods class $tName(..$params) {
        def toMap(): Map[String, Any] = Map[String, Any](..$keyValues)
      }
    """

    println("============== result ==============")
    println(res)
    println("====================================")
    res
  }
} 
开发者ID:mpollmeier,项目名称:scalameta-tutorial,代码行数:28,代码来源:mappable.scala


示例7: IgnoreLogging

//设置package包名称以及导入依赖的类
import scala.annotation.StaticAnnotation
import scala.meta._

class IgnoreLogging extends StaticAnnotation {
  inline def apply(defn: Any): Any = meta {
    defn match {
      case q"..$mods def $ename[..$tparams](...$paramss): $tpeopt = $expr"
        if {
          val modsStr = mods.map(_.structure)
          modsStr.contains(mod"abstract".structure) && modsStr.contains(mod"override".structure)
        } =>
        val paramssTerm = paramss.map(_.map(param => Term.Name(param.name.value)))
        val tparamsTerm = tparams.map(tparam => Type.Name(tparam.name.value))
        if (paramssTerm.nonEmpty && tparamsTerm.nonEmpty) {
          q"""..$mods def $ename[..$tparams](...$paramss): $tpeopt =
           super.$ename[..$tparamsTerm](...$paramssTerm)
          """
        } else if (paramssTerm.nonEmpty && tparamsTerm.isEmpty) {
          q"""..$mods def $ename(...$paramss): $tpeopt =
           super.$ename(...$paramssTerm)
          """
        } else if (paramssTerm.isEmpty && tparamsTerm.nonEmpty) {
          q"""..$mods def $ename[..$tparams]: $tpeopt =
           super.$ename[..$tparamsTerm]
          """
        } else {
          q"""..$mods def $ename: $tpeopt =
           super.$ename
          """
        }
      case _ =>
        abort("@IgnoreLogging can only be used on override def with super callable.")
    }
  }
} 
开发者ID:cuzfrog,项目名称:simple-logging,代码行数:36,代码来源:IgnoreLogging.scala


示例8: Benchmark

//设置package包名称以及导入依赖的类
package io.flatmap.ml.macros

import scala.annotation.{StaticAnnotation, compileTimeOnly}
import scala.meta._

@compileTimeOnly("@Benchmark annotation not expanded")
class Benchmark extends StaticAnnotation {

  inline def apply(defn: Any): Any = meta {
    defn match {
      case q"..$mods def $name[..$tparams](...$argss): $tpeopt = $expr" =>
        println("Parameters: " + argss)
        q"""
          ..$mods def $name[..$tparams](...$argss): $tpeopt = {
           val start = System.nanoTime()
           val result = $expr
           val end = System.nanoTime()
           println(${name.toString} + " elapsed time: " + (end - start) + "ns")
           result
          }
        """
      case _ => abort("@Benchmark annotation works only on methods")
    }
  }

} 
开发者ID:ShokuninSan,项目名称:som,代码行数:27,代码来源:Benchmark.scala


示例9: codegen

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

import java.io.File
import scala.collection.immutable.Seq
import scala.meta._
import scala.annotation.StaticAnnotation
import org.json4s._
import org.json4s.native.JsonMethods._

class codegen extends StaticAnnotation {
  inline def apply(defn: Any): Any = meta {
    implicit val formats = DefaultFormats

    val json = parse(FileInput(new File("domain.json")))
    def classes = json.extract[Map[String, List[(String, String)]]].map {
      case (name, members) => 
        val membersTerms: Seq[Term.Param] = members.map {
          case (name, domainType) =>
            val paramName = Term.Name(name)
            val tpe = toScalaType(domainType)
            param"$paramName: $tpe"
        }
        val tName = Type.Name(name.capitalize)
        q"case class $tName(..$membersTerms)"
    }.toList

    def toScalaType(domainType: String): Type = domainType match {
      case "int" => t"Int"
      case "string" => t"String"
    }

    defn match {
      case obj: Defn.Object =>
        val ret = q"object ${obj.name} {..$classes}"
        println(ret)
        ret
    }
  }
} 
开发者ID:mpollmeier,项目名称:scalameta-tutorial-scaladays,代码行数:40,代码来源:codegen.scala


示例10: RandomStrings

//设置package包名称以及导入依赖的类
package com.terkhorn.randomhell

import scala.annotation.StaticAnnotation
import scala.meta._
import scala.util.Random


class RandomStrings extends StaticAnnotation {
  inline def apply(defn: Any): Any = meta {
    defn match {
      case fn: Defn.Def => RandomStrings.expandDef(fn)
      case t: Term => RandomStrings.expandTerm(t)
      case other => abort(other.pos, "@RandomStrings must annotate a method.")
    }
  }
}

object Randomize {
  private val rnd = new Random
}

trait Randomize {
  def randomize(s: String): String = Randomize.rnd.alphanumeric.take(s.length).mkString
}

object RandomStrings {


  private[randomhell] def expandDef(fn: Defn.Def)(implicit rnd: Randomize = new Randomize {}) =
    fn.copy(body = RandomStrings.expandTerm(fn.body))

  private def expandStat(stat: Stat)(implicit rnd: Randomize = new Randomize {}): Stat = stat match {
    case t: Term => expandTerm(t)
    case q"val ${Pat.Var.Term(n)} = $v" =>
      q"val ${Pat.Var.Term(n)} = ${expandTerm(v)}"
    case q"var ${Pat.Var.Term(n)} = ${Some(v)}" =>
      q"var ${Pat.Var.Term(n)} = ${expandTerm(v)}"
    case fn: Defn.Def => fn.copy(body = RandomStrings.expandTerm(fn.body))
    case other => other
  }

  private[randomhell] def expandTerm(expr: Term)(implicit rnd: Randomize = new Randomize {}): Term = expr match {
    case Lit(s: String) => Lit.String(rnd.randomize(s))
    case Term.Block(stats) => Term.Block(stats.map(c => RandomStrings.expandStat(c)))
    case Term.Return(e) => Term.Return(RandomStrings.expandTerm(e))
    case other => other
  }


} 
开发者ID:felixt-cake,项目名称:scala-random-hell,代码行数:51,代码来源:RandomStrings.scala


示例11: HelloTranslator

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

import scala.reflect.macros.whitebox.Context
import scala.language.experimental.macros
import scala.annotation.{StaticAnnotation, compileTimeOnly}

class HelloTranslator[C <: Context](val context: C) {
  import context.universe._

  case class ObjectPattern(name: TermName, parents: List[Tree], body: List[Tree])

  object ObjectPattern {
    def unapply(tree: Tree): Option[ObjectPattern] = tree match {
      case q"object $name extends ..$parents { ..$body }" => Some(ObjectPattern(name, parents, body))
      case _ => None
    }
  }

  def translate(tree: Tree): Tree = tree match {
    case ObjectPattern(pattern) => translate(pattern)
    case _ => context.abort(context.enclosingPosition, "Cannot match object pattern")
  }

  def translate(pattern: ObjectPattern): Tree = {
    import pattern._

    q"""
      object $name extends ..$parents {
        def hello: ${typeOf[String]} = "hello"
        ..$body
      }
    """
  }
}

object HelloTranslator {
  def apply(c: Context): HelloTranslator[c.type] = new HelloTranslator(c)
}

object HelloMacro {
  def impl(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
    import c.universe._

    val translator = HelloTranslator(c)
    val trees = annottees.map(_.tree).toList
    val translated = translator.translate(trees.head) :: trees.tail
    c.Expr[Any](q"..$translated")
  }
}

@compileTimeOnly("only for compile time expansion")
class hello extends StaticAnnotation {
  def macroTransform(annottees: Any*): Any = macro HelloMacro.impl
} 
开发者ID:cornerman,项目名称:macroni,代码行数:55,代码来源:Hello.scala


示例12: ScmdDef

//设置package包名称以及导入依赖的类
import com.github.cuzfrog.scmd.macros.MacroUtil
import com.github.cuzfrog.scmd.{ScmdRouteDSL, ScmdSafeValueConverter, ScmdTreeDefDSL, ScmdValidationApi, ScmdValueConverter, ScmdValueImplicitConversion}

import scala.annotation.StaticAnnotation
import scala.meta._


package object Scmd extends ScmdValidationApi {

  final val scmdTreeDefDSL: ScmdTreeDefDSL.type = ScmdTreeDefDSL
  final val scmdRouteDSL: ScmdRouteDSL.type = ScmdRouteDSL
  final val scmdValueImplicitConversion: ScmdValueImplicitConversion.type = ScmdValueImplicitConversion
  final val scmdValueConverter: ScmdValueConverter.type = ScmdValueConverter
  final val scmdSafeValueConverter: ScmdSafeValueConverter.type = ScmdSafeValueConverter

  // --------------------- Macro Annotations ----------------------
  final class ScmdDef extends StaticAnnotation {
    inline def apply(defn: Any): Any = meta {
      MacroUtil('Def, defn)
    }
  }
  final class ScmdValid extends StaticAnnotation {
    inline def apply(defn: Any): Any = meta {
      MacroUtil('Valid, defn)
    }
  }
} 
开发者ID:cuzfrog,项目名称:simple-cmd,代码行数:28,代码来源:package.scala


示例13: EqualityOverridingMacro

//设置package包名称以及导入依赖的类
package com.github.cuzfrog.scmd.internal

import scala.annotation.StaticAnnotation
import scala.collection.immutable
import scala.meta._


private[scmd] class EqualityOverridingMacro extends StaticAnnotation {
  inline def apply(defn: Any): Any = meta {
    defn match {
      case Defn.Class(mods, name, tparams, ctor, template) =>
        EqualityOverridingImpl.expand(mods, name, tparams, ctor, template)
      case Term.Block(
      Seq(Defn.Class(mods, name, tparams, ctor, template),
      companion: Defn.Object)) =>
        Term.Block(
          immutable.Seq(
            EqualityOverridingImpl.expand(mods, name, tparams, ctor, template),
            companion)
        )
      case _ =>
        abort(s"@EqualityOverridingMacro must annotate a class.")
    }
  }
}

private object EqualityOverridingImpl {
  final def expand(mods: immutable.Seq[Mod],
                   name: Type.Name,
                   tparams: immutable.Seq[Type.Param],
                   ctor: Ctor.Primary,
                   template: Template): Defn.Class = {
    val Ctor.Primary(_, _, paramss) = ctor
    require(
      paramss.flatten.collectFirst {
        case [email protected](_, Term.Name("entity"), _, _) => p
      }.nonEmpty,
      s"No param named entity found in class ${name.value}."
    )

    val nameWithTpe = if(tparams.nonEmpty) t"$name[_]" else name

    val moreStats = immutable.Seq(
      q"override def hashCode(): Int = entity.hashCode * 3 + 17",
      q"""override def equals(obj: scala.Any): Boolean = {
            if (!this.canEqual(obj)) return false
            obj.asInstanceOf[$nameWithTpe].entity == this.entity
          }""",
      q"override def canEqual(that: Any): Boolean = that.isInstanceOf[$nameWithTpe]"
    )

    val updatedTemplate =
      template.copy(stats = Option(moreStats).map(_ ++ template.stats.getOrElse(Nil)))
    Defn.Class(mods, name, tparams, ctor, updatedTemplate)
  }
} 
开发者ID:cuzfrog,项目名称:simple-cmd,代码行数:57,代码来源:EqualityOverridingMacro.scala


示例14: IgnoreLogging

//设置package包名称以及导入依赖的类
package com.github.cuzfrog.scmd.internal

import scala.annotation.StaticAnnotation
import scala.meta._

private[scmd] class IgnoreLogging extends StaticAnnotation {
  inline def apply(defn: Any): Any = meta {
    defn match {
      case q"..$mods def $ename[..$tparams](...$paramss): $tpeopt = $expr"
        if {
          val modsStr = mods.map(_.structure)
          modsStr.contains(mod"abstract".structure) && modsStr.contains(mod"override".structure)
        } =>
        val paramssTerm = paramss.map(_.map(param => Term.Name(param.name.value)))
        val tparamsTerm = tparams.map(tparam => Type.Name(tparam.name.value))
        if (paramssTerm.nonEmpty && tparamsTerm.nonEmpty) {
          q"""..$mods def $ename[..$tparams](...$paramss): $tpeopt =
           super.$ename[..$tparamsTerm](...$paramssTerm)
          """
        } else if (paramssTerm.nonEmpty && tparamsTerm.isEmpty) {
          q"""..$mods def $ename(...$paramss): $tpeopt =
           super.$ename(...$paramssTerm)
          """
        } else if (paramssTerm.isEmpty && tparamsTerm.nonEmpty) {
          q"""..$mods def $ename[..$tparams]: $tpeopt =
           super.$ename[..$tparamsTerm]
          """
        } else {
          q"""..$mods def $ename: $tpeopt =
           super.$ename
          """
        }
      case _ =>
        abort("@IgnoreLogging can only be used on override def with super callable.")
    }
  }
} 
开发者ID:cuzfrog,项目名称:simple-cmd,代码行数:38,代码来源:IgnoreLogging.scala


示例15: AppInfoMacro

//设置package包名称以及导入依赖的类
package com.github.cuzfrog.scmd.internal

import scala.annotation.StaticAnnotation
import scala.meta._
import scala.collection.immutable

private[scmd] class AppInfoMacro extends StaticAnnotation {
  inline def apply(defn: Any): Any = meta {
    defn match {
      case Term.Block(
      Seq(q"..$mods class $tname ..$ctorMods (...$paramss)", companion: Defn.Object)) =>
        val basics = paramss.head.collect {
          case param"..$mods $name: Option[String] = $_" =>
            q"${Term.Name(name.value)}.map(v=>(${Lit.String(name.value)},v))"
          case param"..$mods $name: String = $_" =>
            q"Option((${Lit.String(name.value)},${Term.Name(name.value)}))"
        }

        val combineDef =
          q"""private def combineBasics:Seq[(String,String)] = Seq(
                ..$basics
              ).flatten"""

        val result = Term.Block(immutable.Seq(
          q"..$mods class $tname ..$ctorMods (...$paramss){$combineDef}", companion))
        //println(result.syntax)
        result
      case _ =>
        abort("This only work on AppInfo.")
    }
  }
} 
开发者ID:cuzfrog,项目名称:simple-cmd,代码行数:33,代码来源:AppInfoMacro.scala


示例16: Repository

//设置package包名称以及导入依赖的类
package com.zhranklin.ddd.model.annotation

import scala.annotation.StaticAnnotation
import scala.collection.immutable.Seq
import scala.meta._


class Repository extends StaticAnnotation {

  inline def apply(defn: Any): Any = meta {
    defn match {
      case cls @ q"trait $typeName extends ..$parents" ?

        val (parentNames1, entityTypes1) = {
          val parentsStr = parents.map(_.syntax.replaceAll("\\(\\)", ""))
          println(parentsStr.zipWithIndex)
          val withRepos = parentsStr.indexWhere {_.contains("WithRepoOf")}
          val (realParents: Seq[String], wrp :: entityTypes) = parentsStr.splitAt(withRepos)
          ("com.zhranklin.ddd.infra.persistence.repository" +: realParents ++: entityTypes.map(_ + ".Repo"),
            entityTypes)
        }

        val (parentNames, entityTypes) = {
          val parentNameTps: Seq[(String, Boolean)] = parents flatMap {
            case t @ ctor"WithRepoOf[(..$types)]()" ?
              println(types)
              println(s"t: $t")
              types map (tpe ? (tpe.syntax + ".Repo", true))
            case t @ ctor"$typename" ?
              println(s"tt: $t")
              List((typename.syntax.replaceAll("\\(\\)", ""), false))
          }
          (parentNameTps map (_._1), parentNameTps filter(_._2 == true) map (_._1 dropRight 5))
        }

        q"""
            trait $typeName extends ..${parentNames map {Ctor.Name.apply}} {
              import com.zhranklin.ddd.model.{entityObject, Id}
              implicit def read[T, E <: entityObject](id: Id)(implicit mapper: Mapper[T], f: Dmo[T] ? E, classTag: scala.reflect.ClassTag[E]): E = mapper.read(id, classTag.runtimeClass)
              implicit private def writeGen[T, E <: entityObject](e: E)(implicit mapper: Mapper[T], f: E ? Dmo[T]): Unit = mapper.write(e)

              override val write: entityObject ? Unit = {
                ..case ${entityTypes map (n ? p"case e0: ${Type.Name(n)} ? writeGen(e0)")}
              }

            }
        """
    }
  }
} 
开发者ID:zhranklin,项目名称:easy-ddd,代码行数:51,代码来源:Repository.scala


示例17: ExtendScope

//设置package包名称以及导入依赖的类
package com.github.kczulko


import scala.annotation.StaticAnnotation
import scala.language.experimental.macros
import scala.reflect.macros.blackbox

class ExtendScope extends StaticAnnotation {
  def macroTransform(annottees: Any*) = macro ExtendScope.impl
}

object ExtendScope {
  def impl(c: blackbox.Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
    import c.universe._
    val result = annottees.map(_.tree).toList match {
      case q"$mods val $tname: $tpt = $expr" :: Nil =>

        def extractVariableDefinition(list: List[c.Tree]): (Any, c.Tree) = {
          list match {
            case Apply(Select(v, TermName("expandToValWithName")), List(Literal(Constant(n)))) :: _ => (n, v)
            case _ :: t => extractVariableDefinition(t)
            case _ => ???
          }
        }

        val (name, value) = expr match {
          case Apply(Ident(TermName("Seq")), list) =>
            extractVariableDefinition(list)
          case _ => ???
        }

        q"""
           val ${TermName(name.toString)} = $value
           $mods val $tname: $tpt = $expr
         """
    }

    c.Expr(result)
  }
} 
开发者ID:kczulko,项目名称:scala-macro-poc,代码行数:41,代码来源:ExtendScope.scala


示例18: helloMacro

//设置package包名称以及导入依赖的类
package codes.bytes.macros_intro.macros

import scala.reflect.macros.whitebox.Context
import scala.language.experimental.macros
import scala.annotation.{compileTimeOnly, StaticAnnotation}

object helloMacro {
  def impl(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
    import c.universe._

    val result = {
      annottees.map(_.tree).toList match {
        case q"object $name extends ..$parents { ..$body }" :: Nil =>
          q"""
            object $name extends ..$parents {
              def hello: ${typeOf[String]} = "hello"
              ..$body
            }
          """
      }
    }
    c.Expr[Any](result)
  }
}

@compileTimeOnly("enable macro paradise to expand macro annotations")
class hello extends StaticAnnotation {
  def macroTransform(annottees: Any*): Any = macro helloMacro.impl
}

// vim: set ts=2 sw=2 sts=2 et: 
开发者ID:bwmcadams,项目名称:supreme-macro-adventure,代码行数:32,代码来源:AnnotationMacro.scala


示例19: Bootstrap

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

import be.doeraene.sjsreflect.Reflect

import scala.annotation.{StaticAnnotation, compileTimeOnly}
import scala.meta._


@compileTimeOnly("@Bootstrap not expanded")
class Bootstrap extends StaticAnnotation {
  inline def apply(defn: Any): Any = meta {

    val q"object $tname extends ..$parents { ..$stats }" = defn

    // should evaluate something like:
    // app.AppModule.annotations = app.AppModule_().annotations
    // for every class that extends NGAnnotations
    val propertyApplication =
      q"""
         be.doeraene.sjsreflect.Reflect
         .enumerateClasses
         // gets the fully qualified class-name
         .map(_.getName)
         .withFilter(_ != "ng.macros.NGAnnotation")
         .foreach(className => {
           val objName = "annots." + className.split('.').last + "_()"

           val expr =
           s"$$className.annotations = $$objName.annotations; $$className.parameters = $$objName.parameters"

           scalajs.js.eval(expr)
         })
       """


    q"object $tname extends ..$parents { $propertyApplication; ..$stats }"
  }
} 
开发者ID:AugustNagro,项目名称:scalajs-ng,代码行数:39,代码来源:Bootstrap.scala


示例20: DefaultReaderMacroOf

//设置package包名称以及导入依赖的类
package org.zalando.grafter.macros

import scala.annotation.StaticAnnotation
import ReaderMacros._

import scala.meta._
import DefaultReaderMacroOf._

object DefaultReaderMacroOf {

  val annotationName = "defaultReaderOf"

  def expand(traitDef: Defn.Trait, objectDef: Option[Defn.Object], configTypeParam: Type.Name, typeParam: Type.Name): Term.Block = {
    output(traitDef, objectDef) {
      q"""
         implicit def reader(implicit defaultReader: cats.data.Reader[$configTypeParam, $typeParam]): cats.data.Reader[$configTypeParam, ${traitDef.name}] =
           org.zalando.grafter.GenericReader.widenReader(defaultReader)
      """
    }
  }

}

class defaultReaderOf[A, B] extends StaticAnnotation {

  inline def apply(defn: Any): Any = meta {
    val (traitDef, objectDef) = annotatedTrait(annotationName)(defn)
    DefaultReaderMacroOf.expand(traitDef, objectDef, Type.Name(A.toString), Type.Name(B.toString))
  }

} 
开发者ID:zalando,项目名称:grafter,代码行数:32,代码来源:DefaultReaderOfMacro.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala StringType类代码示例发布时间:2022-05-23
下一篇:
Scala LabeledPoint类代码示例发布时间: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