当前位置: 首页>>代码示例>>Scala>>正文


Scala macros类代码示例

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


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


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