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

Scala macros类代码示例

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

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



在下文中一共展示了macros类的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: DslMacros

//设置package包名称以及导入依赖的类
package io.scalaland.chimney

import scala.language.experimental.macros

private[chimney] object DslMacros {
  def constFieldSelector(c: scala.reflect.macros.whitebox.Context)(selector: c.Tree, value: c.Tree): c.Tree = {
    import c.universe._
    selector match {
      case q"(${vd: ValDef}) => ${idt: Ident}.${fieldName: Name}" if vd.name == idt.name =>
        val sym = Symbol(fieldName.decodedName.toString)
        q"{${c.prefix}}.withFieldConst($sym, $value)"
      case _ =>
        c.abort(c.enclosingPosition, "Invalid selector!")
    }
  }

  def computedFieldSelector(c: scala.reflect.macros.whitebox.Context)(selector: c.Tree, map: c.Tree): c.Tree = {
    import c.universe._
    selector match {
      case q"(${vd: ValDef}) => ${idt: Ident}.${fieldName: Name}" if vd.name == idt.name =>
        val sym = Symbol(fieldName.decodedName.toString)
        q"{${c.prefix}}.withFieldComputed($sym, $map)"
      case _ =>
        c.abort(c.enclosingPosition, "Invalid selector!")
    }
  }

  def renamedFieldSelector(c: scala.reflect.macros.whitebox.Context)(selectorFrom: c.Tree, selectorTo: c.Tree): c.Tree = {
    import c.universe._
    (selectorFrom, selectorTo) match {
      case (
          q"(${vdF: ValDef}) => ${idtF: Ident}.${fromFieldName: Name}",
          q"(${vdT: ValDef}) => ${idtT: Ident}.${toFieldName: Name}"
          ) if vdF.name == idtF.name && vdT.name == idtT.name =>
        val symFrom = Symbol(fromFieldName.decodedName.toString)
        val symTo = Symbol(toFieldName.decodedName.toString)
        q"{${c.prefix}}.withFieldRenamed($symFrom, $symTo)"
      case (q"(${vd: ValDef}) => ${idt: Ident}.${_: Name}", sel @ _) if vd.name == idt.name =>
        c.abort(c.enclosingPosition, s"Selector of type ${sel.tpe} is not valid: $sel")
      case (sel @ _, q"(${vd: ValDef}) => ${idt: Ident}.${_: Name}") if vd.name == idt.name =>
        c.abort(c.enclosingPosition, s"Selector of type ${sel.tpe} is not valid: $sel")
      case (sel1, sel2) =>
        val inv1 = s"Selector of type ${sel1.tpe} is not valid: $sel1"
        val inv2 = s"Selector of type ${sel2.tpe} is not valid: $sel2"
        c.abort(c.enclosingPosition, s"Invalid selectors:\n$inv1\n$inv2")
    }
  }

} 
开发者ID:scalalandio,项目名称:chimney,代码行数:50,代码来源:DslMacros.scala


示例3: scoped

//设置package包名称以及导入依赖的类
package io.scalajs.npm.angularjs

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


object scoped {

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

    annottees map (_.tree) match {
      case (decl @ DefDef(mods, name, tparams, vparamss, tpt, rhs)) :: Nil =>
        vparamss.headOption match {
          case Some(params) =>
            val args = params.map(_.name)
            q"""
            $decl
            $$scope.asInstanceOf[scala.scalajs.js.Dynamic].${decl.name} = (..$params) => ${decl.name}(..$args)"""
          case None =>
            q"""
            $decl
            $$scope.asInstanceOf[scala.scalajs.js.Dynamic].${decl.name} = () => ${decl.name}"""
        }

      case others =>
        others.foreach(other =>
          c.info(c.enclosingPosition, s"other - class type: ${other.getClass.getName}", force = true))
        c.abort(c.enclosingPosition, "A method declaration is required")
    }
  }

} 
开发者ID:scalajs-io,项目名称:angular,代码行数:35,代码来源:scoped.scala


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


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


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


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


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


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


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


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


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

//设置package包名称以及导入依赖的类
package net.scalax.fsn.parameter.helper

import net.scalax.fsn.parameter.atomic.DataMapGen

class ParamGenImpl(val c: scala.reflect.macros.blackbox.Context) {
  import c.universe._
  def apply[Entity: c.WeakTypeTag]: c.Expr[DataMapGen[Entity]] = {
    val entity = c.weakTypeOf[Entity]
    val expr = c.Expr[DataMapGen[Entity]](
      q"""
       new _root_.net.scalax.fsn.parameter.atomic.DataMapGen[$entity] {
         override def apply(s: $entity) = {
           val labelGen = _root_.shapeless.LabelledGeneric[$entity]
           val hlistData = labelGen.to(s)
           import _root_.shapeless.record._
           (_root_.shapeless.ops.record.Keys[labelGen.Repr].apply.toList: List[_root_.scala.Symbol])
           .map(_.name)
           .zip {
             (hlistData.values.toList: List[_root_.net.scalax.fsn.parameter.atomic.FParam[_]])
             .map(_.paramComp)
           }
           .map {
             case (key, value) => value.toContent(key)
           }
         }
       }
     """
    )
    //println(expr.toString())
    expr
  }
}

trait ParamGenImplicit {
  import scala.language.experimental.macros
  implicit def fCompModel2CParamFormater[T]: DataMapGen[T] = macro ParamGenImpl.apply[T]
} 
开发者ID:scalax,项目名称:ubw,代码行数:38,代码来源:ParamGenImpl.scala


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


示例15: TypeUtils

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

import com.google.common.reflect.TypeToken

import scala.language.experimental.macros
import scala.reflect.ClassTag
import scala.reflect.macros.whitebox
import scala.reflect.runtime.{universe => ru}

object TypeUtils {
  @inline def typeTag[T: ru.TypeTag](obj: T): ru.TypeTag[T] = ru.typeTag[T]
  @inline def typeTag[T: ru.TypeTag](cls: Class[T]): ru.TypeTag[T] = ru.typeTag[T]

  @inline def typeOf[T: ru.TypeTag](obj: T): ru.Type = ru.typeOf[T]
  @inline def typeOf[T: ru.TypeTag](cls: Class[T]): ru.Type = ru.typeOf[T]

  @inline def classTag[T: ClassTag](obj: T): ClassTag[T] = scala.reflect.classTag[T]
  @inline def classTag[T: ClassTag](cls: Class[T]): ClassTag[T] = scala.reflect.classTag[T]

  @inline def runtimeClass[T: ClassTag]: Class[T] = implicitly[ClassTag[T]].runtimeClass.asInstanceOf[Class[T]]

  def captureJavaType(typeLiteral: String): java.lang.reflect.Type = macro TypeUtilsMacroImpl.captureJavaType_impl
}

object TypeUtilsMacroImpl {
  def captureJavaType_impl(c: whitebox.Context)(typeLiteral: c.Expr[String]): c.Expr[java.lang.reflect.Type] = {
    import c.universe._
    val typeTokenTypeSymbol = typeOf[TypeToken[_]].typeSymbol
    val Literal(Constant(typeLiteralValue: String)) = typeLiteral.tree
    val q"type T = $typeLiteralTree" = c.parse(s"type T = $typeLiteralValue")
    c.Expr(q"new $typeTokenTypeSymbol[$typeLiteralTree]{}.getType")
  }
} 
开发者ID:stonexx,项目名称:utils,代码行数:34,代码来源:TypeUtils.scala


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


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


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


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


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



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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