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

Scala Context类代码示例

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

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



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

示例1: treeTypeOf

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

import scala.reflect.macros.whitebox.Context

trait PContext {
  val c: Context

  import c.universe._

  def treeTypeOf(t: Tree): Tree = t match {
    case ClassDef(_, name, Seq(), _)   => tq"$name"
    case ClassDef(_, name, tparams, _) => tq"$name[..$tparams]"
    case ModuleDef(_, name, _)         => tq"$name.type"
    case ValDef(_, name, _, _)         => tq"$name.type"
    case DefDef(_, _, _, Nil, tpt, _)  => tpt
    case Typed(_, tpt)                 => tpt
    case _                             => t
  }

  def annotationStringArgs: Vector[String] = c.prefix.tree match {
    case q"new $name( ..$params )" => params.toVector map { case Literal(Constant(s: String)) => s }
    case _                         => Vector()
  }

  def fail(msg: String): Nothing = c.abort(c.enclosingPosition, msg)
  def mkLiftable[A](f: A => Tree): Liftable[A] = new Liftable[A] { def apply(x: A): Tree = f(x) }

  implicit def liftableSymbol: Liftable[Symbol] = mkLiftable(x => Ident(x))

  
  object BlockStats {
    def unapply(t: Tree): Option[List[Tree]] = t match {
      case Block(stats, EmptyTree | Literal(Constant(()))) => Some(stats)
      case _                                               => None
    }
  }
  def unBlockOne(t: Tree): Tree = t match {
    case BlockStats(stat :: Nil) => stat
    case _                       => t
  }
  def unBlock(t: Tree): List[Tree] = t match {
    case BlockStats(stats) => stats
    case t                 => List(t)
  }

  protected def tracing[A](msg: => String)(value: A): A = {
    trace(s"$msg: $value")
    value
  }
  protected def trace(msg: => String): Unit = (
    if (sys.props contains "psply.trace")
      Console.err.println(msg)
  )
} 
开发者ID:paulp,项目名称:psply,代码行数:56,代码来源:PContext.scala


示例2: NoDataMacros

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

import scala.reflect.macros.whitebox.Context

object NoDataMacros {
  def isNoDataByte_impl(ct: Context)(b: ct.Expr[Byte]): ct.Expr[Boolean] = {
    import ct.universe._
    ct.Expr(q"""$b == Byte.MinValue""")
  }

  def isNoDataShort_impl(ct: Context)(s: ct.Expr[Short]): ct.Expr[Boolean] = {
    import ct.universe._
    ct.Expr(q"""$s == Short.MinValue""")
  }

  def isNoDataInt_impl(ct: Context)(i: ct.Expr[Int]): ct.Expr[Boolean] = {
    import ct.universe._
    ct.Expr(q"""$i == Int.MinValue""")
  }

  def isNoDataFloat_impl(ct: Context)(f: ct.Expr[Float]): ct.Expr[Boolean] = {
    import ct.universe._
    ct.Expr(q"""java.lang.Float.isNaN($f)""")
  }

  def isNoDataDouble_impl(ct: Context)(d: ct.Expr[Double]): ct.Expr[Boolean] = {
    import ct.universe._
    ct.Expr(q"""java.lang.Double.isNaN($d)""")
  }

  def isDataByte_impl(ct: Context)(b: ct.Expr[Byte]): ct.Expr[Boolean] = {
    import ct.universe._
    ct.Expr(q"""$b != Byte.MinValue""")
  }

  def isDataShort_impl(ct: Context)(s: ct.Expr[Short]): ct.Expr[Boolean] = {
    import ct.universe._
    ct.Expr(q"""$s != Short.MinValue""")
  }

  def isDataInt_impl(ct: Context)(i: ct.Expr[Int]): ct.Expr[Boolean] = {
    import ct.universe._
    ct.Expr(q"""$i != Int.MinValue""")
  }

  def isDataFloat_impl(ct: Context)(f: ct.Expr[Float]): ct.Expr[Boolean] = {
    import ct.universe._
    ct.Expr(q"""!java.lang.Float.isNaN($f)""")
  }

  def isDataDouble_impl(ct: Context)(d: ct.Expr[Double]): ct.Expr[Boolean] = {
    import ct.universe._
    ct.Expr(q"""!java.lang.Double.isNaN($d)""")
  }

} 
开发者ID:lossyrob,项目名称:geotrellis-before-locationtech,代码行数:57,代码来源:NoDataMacros.scala


示例3: foreachIntVisitor

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

import spire.macros.InlineUtil

import scala.reflect.macros.whitebox.Context

trait MacroIterableTile {
  def foreachIntVisitor(visitor: IntTileVisitor): Unit
  def foreachDoubleVisitor(visitor: DoubleTileVisitor): Unit
}

trait MacroMappableTile[T] {
  def mapIntMapper(mapper: IntTileMapper): T
  def mapDoubleMapper(mapper: DoubleTileMapper): T
}

trait IntTileMapper {
  def apply(col: Int, row: Int, z: Int): Int
}

trait DoubleTileMapper {
  def apply(col: Int, row: Int, z: Double): Double
}

trait IntTileVisitor {
  def apply(col: Int, row: Int, z: Int): Unit
}

trait DoubleTileVisitor {
  def apply(col: Int, row: Int, z: Double): Unit
}

object TileMacros {
  def intMap_impl[T <: MacroMappableTile[T]](c: Context)(f: c.Expr[(Int, Int, Int) => Int]): c.Expr[T] = {
    import c.universe._
    val self = c.Expr[MacroMappableTile[T]](c.prefix.tree)
    val tree = q"""$self.mapIntMapper(new geotrellis.macros.IntTileMapper { def apply(col: Int, row: Int, z: Int): Int = $f(col, row, z) })"""
    new InlineUtil[c.type](c).inlineAndReset[T](tree)
  }

  def doubleMap_impl[T <: MacroMappableTile[T]](c: Context)(f: c.Expr[(Int, Int, Double) => Double]): c.Expr[T] = {
    import c.universe._
    val self = c.Expr[MacroMappableTile[T]](c.prefix.tree)
    val tree = q"""$self.mapDoubleMapper(new geotrellis.macros.DoubleTileMapper { def apply(col: Int, row: Int, z: Double): Double = $f(col, row, z) })"""
    new InlineUtil[c.type](c).inlineAndReset[T](tree)
  }

  def intForeach_impl(c: Context)(f: c.Expr[(Int, Int, Int) => Unit]): c.Expr[Unit] = {
    import c.universe._
    val self = c.Expr[MacroIterableTile](c.prefix.tree)
    val tree = q"""$self.foreachIntVisitor(new geotrellis.macros.IntTileVisitor { def apply(col: Int, row: Int, z: Int): Unit = $f(col, row, z) })"""
    new InlineUtil[c.type](c).inlineAndReset[Unit](tree)
  }

  def doubleForeach_impl(c: Context)(f: c.Expr[(Int, Int, Double) => Unit]): c.Expr[Unit] = {
    import c.universe._
    val self = c.Expr[MacroIterableTile](c.prefix.tree)
    val tree = q"""$self.foreachDoubleVisitor(new geotrellis.macros.DoubleTileVisitor { def apply(col: Int, row: Int, z: Double): Unit = $f(col, row, z) })"""
    new InlineUtil[c.type](c).inlineAndReset[Unit](tree)
  }
} 
开发者ID:lossyrob,项目名称:geotrellis-before-locationtech,代码行数:62,代码来源:TileMacros.scala


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


示例5: toMap

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

import scala.language.experimental.macros
import scala.reflect.macros.whitebox.Context


trait Mappable[T] {

  def toMap(t: T): Map[String, Any]

  def fromMap(map: Map[String, Any]): T

}

object Mappable {
  implicit def materializeMappable[T]: Mappable[T] =
  macro materializeMappableImpl[T]

  def materializeMappableImpl[T: c.WeakTypeTag](c: Context): c.Expr[Mappable[T]] = {
    import c.universe._
    val tpe = weakTypeOf[T]
    val companion = tpe.typeSymbol.companion
    val fields = tpe.decls.collectFirst {
      case m: MethodSymbol if m.isPrimaryConstructor ? m
    }.get.paramLists.head

    val (toMapParams, fromMapParams) = fields.map { field ?
      val name = field.asTerm.name
      val decoded = name.decodedName.toString
      val returnType = tpe.decl(name).typeSignature

      (q"$decoded ? t.$name", q"map($decoded).asInstanceOf[$returnType]")
    }.unzip

    c.Expr[Mappable[T]] { q"""
      new Mappable[$tpe] {
        def toMap(t: $tpe): Map[String, Any] = Map(..$toMapParams)
        def fromMap(map: Map[String, Any]): $tpe = $companion(..$fromMapParams)
      }
      """
    }
  }
} 
开发者ID:hailg,项目名称:facebook-scala-ads-sdk,代码行数:44,代码来源:Mappable.scala


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


示例7: PrintfMacros

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

import scala.language.experimental.macros
import scala.reflect.macros.whitebox.Context
import scala.collection.mutable.{ListBuffer, Stack}

object PrintfMacros {
  def printf(format: String, params: Any*): Unit = macro printf_impl

  def printf_impl(c: Context)(format: c.Expr[String], params: c.Expr[Any]*): c.Expr[Unit] = {
    import c.universe._
    val Literal(Constant(s_format: String)) = format.tree
    val evals = ListBuffer[ValDef]()
    def precompute(value: Tree, tpe: Type): Ident = {
      val freshName = TermName(c.freshName("eval$"))
      evals += ValDef(Modifiers(), freshName, TypeTree(tpe), value)
      Ident(freshName)
    }
    val paramsStack = Stack[Tree]((params map (_.tree)): _*)
    val refs = s_format.split("(?<=%[\\w%])|(?=%[\\w%])") map {
      case "%d" => precompute(paramsStack.pop, typeOf[Int])
      case "%s" => precompute(paramsStack.pop, typeOf[String])
      case "%%" => Literal(Constant("%"))
      case part => Literal(Constant(part))
    }
    val stats = evals ++ refs.map(ref => reify(print(c.Expr[Any](ref).splice)).tree)
    c.Expr[Unit](Block(stats.toList, Literal(Constant(()))))
  }
}

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



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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