本文整理汇总了Scala中scala.reflect.macros.blackbox.Context类的典型用法代码示例。如果您正苦于以下问题:Scala Context类的具体用法?Scala Context怎么用?Scala Context使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Context类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: MacroImpl
//设置package包名称以及导入依赖的类
package underscoreio
package holes
import scala.reflect.macros.blackbox.Context
object MacroImpl {
def hole(c: Context): c.Tree = {
import c.universe._
val targetType: Option[c.universe.Type] = {
c.internal.enclosingOwner match {
case ts: TermSymbol =>
println(s"Symbol: $ts, signature: ${ts.typeSignature}")
Some(ts.typeSignature.finalResultType)
case o =>
c.error(c.enclosingPosition, "Hole macro impcomplete: doesn't know what to do with {o.getClass}")
None
}
}
targetType match {
case Some(t) => c.error(c.enclosingPosition, s"Hole found which needs to be filled with type: ${t}")
case None => c.error(c.enclosingPosition, "Hole exists, but type to fill cannot be determined")
}
q"???"
}
}
示例2: 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")""")
}
}
示例3: 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
}
}
示例4: 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")
}
}
}
示例5: 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)"
}
}
示例6: 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) }"
}
}
示例7: 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
}
"""
}
}
示例8: 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]
}
"""
}
}
示例9: Reader
//设置package包名称以及导入依赖的类
package parsec.optimised
import scala.reflect.macros.blackbox.Context
import util.Zeroval
trait ReaderOps {
val c: Context
import c.universe._
abstract class Reader(elemType: Type) {
def first: Tree
def atEnd: Tree
def rest: Reader
}
abstract class CharReader extends Reader(typeOf[Char]) { self =>
def apply(cont: (Tree, Tree) => Tree): Tree
def first = self.apply((source, pos) => q"$source($pos)")
def atEnd = self.apply((source, pos) => q"$pos >= $source.length")
def rest = new CharReader {
def apply(cont: (Tree, Tree) => Tree) =
self.apply((source, pos) => cont(source, q"$pos + 1"))
}
def getSource = self.apply((src, _) => src)
def getPos = self.apply((_, p) => p)
def toCharReader: Tree = self.apply {
//(source, pos) => q"CharReader(${source.symbol}, ${pos.symbol})"
(source, pos) => q"CharReader($source, $pos)"
}
}
def mkCharReader(source: Tree, pos: Tree) = new CharReader {
def apply(cont: (Tree, Tree) => Tree) = cont(source, pos)
}
def cond(test: Tree, thenp: CharReader, elsep: CharReader) = {
new CharReader {
def apply(cont: (Tree, Tree) => Tree) = {
q"""
if ($test) ${thenp(cont)}
else ${elsep(cont)}
"""
}
}
}
}
示例10: zeroValue
//设置package包名称以及导入依赖的类
package parsec.optimised.util
import scala.reflect.macros.blackbox.Context
trait Zeroval {
val c: Context
import c.universe._
//scalastyle:off line.size.limit
//scalastyle:on line.size.limit
def zeroValue(typ: Type): Tree = {
if (typ =:= typeOf[scala.Char]) q"0"
else if (typ =:= typeOf[scala.Int]) q"0"
else if (typ =:= typeOf[scala.Unit]) q"()"
else if (typ =:= typeOf[scala.Double]) q"0.0"
else q"null"
}
}
示例11: OrigOwnerAttachment
//设置package包名称以及导入依赖的类
package macroutil {
import scala.reflect.macros.blackbox.Context
case class OrigOwnerAttachment(sym: Any)
object Splicer {
import scala.reflect.macros._
import blackbox.Context
def impl[A](c: Context)(expr: c.Expr[A]): c.Expr[A] = {
val helper = new Splicer[c.type](c)
c.Expr[A](helper.changeOwner(expr.tree))
}
class Splicer[C <: Context](val c: C) {
import c.universe._
import c.universe.definitions._
import c.internal._, decorators._
def changeOwner(tree: c.Tree): c.Tree = {
import c.universe._, internal._, decorators._
val origOwner = tree.attachments.get[OrigOwnerAttachment].map(_.sym).get.asInstanceOf[Symbol]
c.internal.changeOwner(tree, origOwner, c.internal.enclosingOwner)
}
}
def changeOwner[A](expr: A): A = macro impl[A]
}
}
示例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 + "\""
"""
}
}
示例13: TestTransformer
//设置package包名称以及导入依赖的类
package tryp.test.fixtures
import scala.reflect.macros.blackbox.Context
import annotation.StaticAnnotation
import tryp.Annotation
trait TestAnnotationBase
extends Annotation
{
import c.universe._
object TestTransformer
extends Transformer
{
def apply(annottees: Annottees) = {
annottees
}
}
override def transformers = TestTransformer :: Nil
}
class Test
extends StaticAnnotation
{
def macroTransform(annottees: Any*) = macro TestAnnotation.process
}
class TestAnnotation(val c: Context)
extends TestAnnotationBase
示例14: MacrosImpl
//设置package包名称以及导入依赖的类
package io.bluecabin.common.macros
import scala.annotation.tailrec
import scala.reflect.macros.blackbox.Context
private[macros] object MacrosImpl {
def singletonsImpl[A: c.WeakTypeTag](c: Context): c.Expr[Traversable[A]] = {
import c.universe._
val A = weakTypeOf[A]
val typeSym = A.typeSymbol
val singletonIdents = if ((typeSym.isClass) && (typeSym.asClass.isSealed)) {
@tailrec def topParentInPackage(s: c.universe.Symbol): c.universe.Symbol = {
val owner = s.owner
if (owner.isPackage) owner else if (owner == NoSymbol) s else topParentInPackage(owner)
}
@tailrec def nestedSingletons(inputs: Vector[c.universe.Symbol], currResult: Vector[c.universe.Symbol])
(filter: c.universe.ModuleSymbol => Boolean): Vector[c.universe.Symbol] = {
inputs.headOption match {
case Some(m: ModuleSymbol) =>
val newResult = if (filter(m)) currResult :+ m else currResult
nestedSingletons(m.typeSignature.decls.toVector ++ inputs.tail, newResult)(filter)
case Some(m: ClassSymbol) => nestedSingletons(m.typeSignature.decls.toVector ++ inputs.tail, currResult)(filter)
case Some(s) =>
nestedSingletons(inputs.tail, currResult)(filter)
case None => currResult
}
}
val top = topParentInPackage(c.internal.enclosingOwner)
nestedSingletons(Vector(top), Vector.empty) { m =>
m.typeSignature.baseClasses.contains(typeSym)
} map (Ident(_))
} else {
c.abort(
c.enclosingPosition,
"Only sealed traits or classes are allowed"
)
}
c.Expr[Traversable[A]](q"Traversable(..$singletonIdents)")
}
}
示例15: debug
//设置package包名称以及导入依赖的类
package io.flatmap.ml.macros
import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Context
object debug {
def apply[T](x: => T): T = macro impl
def impl(c: Context)(x: c.Tree) = { import c.universe._
val q"..$stats" = x
val loggedStats = stats.flatMap { stat =>
val msg = "executing " + stat
List(q"println($msg)", stat)
}
q"..$loggedStats"
}
}