本文整理汇总了Scala中scala.annotation.StaticAnnotation类的典型用法代码示例。如果您正苦于以下问题:Scala StaticAnnotation类的具体用法?Scala StaticAnnotation怎么用?Scala StaticAnnotation使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了StaticAnnotation类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
}
}
示例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)")
}
}
示例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")
}
}
}
示例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
}
示例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
}
示例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
}
}
示例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.")
}
}
}
示例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")
}
}
}
示例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
}
}
}
示例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
}
}
示例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
}
示例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)
}
}
}
示例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)
}
}
示例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.")
}
}
}
示例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.")
}
}
}