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


Scala whitebox类代码示例

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


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

示例1: CoproductMacros

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

import scala.reflect.macros.whitebox

import shapeless.{:+:, CNil}

class CoproductMacros(val c: whitebox.Context) {
  import c.universe._

  
  def callAcceptCoproduct(types: Tree*): Tree = {
    val lhs = c.prefix.tree
    val accepts = types map {
      case Literal(const @ Constant(str: String)) => c.internal.constantType(const)
      case other => c.abort(c.enclosingPosition, s"$other is not a string constant")
    }

    val cnil = weakTypeOf[CNil]
    val ccons = weakTypeOf[:+:[_, _]].typeConstructor

    val coproductType =
      accepts.foldRight(cnil) { case (elemTpe, acc) =>
        appliedType(ccons, List(elemTpe, acc))
      }

    q"$lhs.accept[$coproductType]"
  }
} 
开发者ID:finagle,项目名称:featherbed,代码行数:29,代码来源:CoproductMacros.scala

示例2: SamuraiMacros

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

import scala.reflect.macros.whitebox

object SamuraiMacros {

  def instImpl(c: whitebox.Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
    import c.universe._
    val (inst: ValOrDefDef) :: Nil = annottees.map(_.tree).toList

    val samFunction = inst.rhs match {
      case f: Function => f
      case _ =>
        c.abort(c.enclosingPosition, "@sam annotation requires a function definition!")
    }

    val (tcName, wildcards) = inst.tpt match {
      case att: AppliedTypeTree =>
        (att.tpt.asInstanceOf[Ident].name, att.args.map(_ => "_").mkString("[", ",", "]"))
      case idt: Ident =>
        (idt.name, "")
    }

    val ttt = c.parse(s"val x: $tcName$wildcards = null").asInstanceOf[ValDef]
    val tcFullName = c.typecheck(q"??? : ${ttt.asInstanceOf[ValDef].tpt}").tpe.typeSymbol.fullName
    val tcClz = c.mirror.staticClass(tcFullName)
    val abstractMembers = tcClz.typeSignature.members.filter(_.isAbstract)

    abstractMembers.toList match {
      case List(m) =>

        val samSymbol = m.asMethod
        val samName = samSymbol.name.toTermName

        val samDefTree = q"def $samName(..${samFunction.vparams}) = ${samFunction.body}"
        val instRhs = q"new ${inst.tpt} { $samDefTree }"

        val tree =
          inst match {
            case dd: DefDef =>
              q"${dd.mods} def ${dd.name}[..${dd.tparams}](...${dd.vparamss}): ${dd.tpt} = $instRhs"

            case vd: ValDef =>
              q"${vd.mods} val ${vd.name}: ${vd.tpt} = $instRhs"
          }

        c.Expr[Any](tree)

      case ms =>
        c.abort(
          c.enclosingPosition,
          s"$tcClz has not single abstract method, but ${ms.size} ${ms.map(_.name).mkString("(",", ", ")")}"
        )
    }
  }
} 
开发者ID:scalalandio,项目名称:samurai,代码行数:57,代码来源:SamuraiMacros.scala

示例3: SamuraiMacros

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

import scala.reflect.macros.whitebox

object SamuraiMacros {

  def instImpl(c: whitebox.Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
    import c.universe._
    val (inst: ValOrDefDef) :: Nil = annottees.map(_.tree).toList

    inst.rhs match {
      case _: Function =>
        c.Expr[Any](q"$inst")
      case _ =>
        c.abort(c.enclosingPosition, "@sam annotation requires a function definition!")
    }
  }
} 
开发者ID:scalalandio,项目名称:samurai,代码行数:19,代码来源:SamuraiMacros.scala

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

示例5: unsafeCheck

//设置package包名称以及导入依赖的类
package singleton.twoface.impl

import macrocompat.bundle
import singleton.ops._
import singleton.ops.impl._
import scala.reflect.macros.whitebox

trait CheckedAny[Face, T] extends Any with TwoFaceAny[Face, T] {
  def unsafeCheck[ParamFace, Cond[_,_], Msg[_,_]](p : Option[ParamFace] = None)
  (implicit rt : RunTime[T],
   rtc : singleton.twoface.Checked.Runtime[Face, ParamFace, Cond, Msg]) : this.type = {
    if (rt) require(rtc.cond(getValue,p), rtc.msg(getValue,p))
    this
  }
}

object CheckedAny {
  trait Builder[Chk[_,C[_,_],_,M[_,_]], Face] {
    type CondHelper[Cond[_,_], T, Param] = ITE[IsNotLiteral[Cond[T, Param]], true, Cond[T, Param]]
    type MsgHelper[Msg[_,_], T, Param] = ITE[IsNotLiteral[Msg[T, Param]], "Something bad happened", Msg[T, Param]]
    protected def create[T, Cond[_,_], Param, Msg[_,_]](value : Face) : Chk[T, Cond, Param, Msg]

    implicit def impl[T, Cond[_,_], Param, Msg[_,_]]
      (implicit vc : CondHelper[Cond, T, Param], vm : MsgHelper[Msg, T, Param]) :
      Chk[T, Cond, Param, Msg] = macro Builder.Macro.impl[T, Cond, Param, Msg, Chk[T, Cond, Param, Msg]]

    implicit def safe[T <: Face with Singleton, Cond[_,_], Param, Msg[_,_]]
      (value : T)(implicit vc : CondHelper[Cond, T, Param], vm : MsgHelper[Msg, T, Param]) :
      Chk[T, Cond, Param, Msg] = macro Builder.Macro.safe[T, Cond, Param, Msg, Chk[T, Cond, Param, Msg]]

    implicit def unsafe[Cond[_,_], Param, Msg[_,_]](value : Face) :
      Chk[Face, Cond, Param, Msg] = create[Face, Cond, Param, Msg](value)

    implicit def safeTF[T <: Face with Singleton, Cond[_,_], Param, Msg[_,_]]
      (value : TwoFaceAny[Face, T])(implicit vc : CondHelper[Cond, T, Param], vm : MsgHelper[Msg, T, Param]) :
      Chk[T, Cond, Param, Msg] = macro Builder.Macro.safeTF[T, Cond, Param, Msg, Chk[T, Cond, Param, Msg]]

    implicit def unsafeTF[Cond[_,_], Param, Msg[_,_]](tf : TwoFaceAny[Face, Face]) :
      Chk[Face, Cond, Param, Msg] = create[Face, Cond, Param, Msg](tf.getValue)
  }

  @bundle
  object Builder {
    final class Macro(val c: whitebox.Context) extends GeneralMacros {
      def impl[T, Cond[_,_], Param, Msg[_,_], Chk](vc : c.Tree, vm : c.Tree)(
        implicit
        t : c.WeakTypeTag[T], cond : c.WeakTypeTag[Cond[_,_]], msg : c.WeakTypeTag[Msg[_,_]], param: c.WeakTypeTag[Param], chk: c.WeakTypeTag[Chk]
      ): c.Tree = CheckedImplMaterializer[T, Cond[_,_], Param, Msg[_,_], Chk].impl(vc, vm)

      def safe[T, Cond[_,_], Param, Msg[_,_], Chk](value : c.Tree)(vc : c.Tree, vm : c.Tree)(
        implicit
        t : c.WeakTypeTag[T], cond : c.WeakTypeTag[Cond[_,_]], msg : c.WeakTypeTag[Msg[_,_]], param: c.WeakTypeTag[Param], chk: c.WeakTypeTag[Chk]
      ): c.Tree = CheckedImplMaterializer[T, Cond[_,_], Param, Msg[_,_], Chk].impl(vc, vm)

      def safeTF[T, Cond[_,_], Param, Msg[_,_], Chk](value : c.Tree)(vc : c.Tree, vm : c.Tree)(
        implicit
        t : c.WeakTypeTag[T], cond : c.WeakTypeTag[Cond[_,_]], msg : c.WeakTypeTag[Msg[_,_]], param: c.WeakTypeTag[Param], chk: c.WeakTypeTag[Chk]
      ): c.Tree = CheckedImplMaterializer[T, Cond[_,_], Param, Msg[_,_], Chk].impl(vc, vm)
    }
  }
} 
开发者ID:fthomas,项目名称:singleton-ops,代码行数:62,代码来源:CheckedAny.scala

示例6: GogglesMacros

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

import goggles.macros.errors.ErrorMessages
import goggles.macros.interpret.{MacroResult, MacroInterpreter, DslMode}

import scala.reflect.macros.whitebox


object GogglesMacros {

  def getImpl(c: whitebox.Context)(args: c.Expr[Any]*): c.Tree = {
    handleResult(c)(MacroInterpreter.getImpl(c)(args: _*), DslMode.Get)
  }

  def setImpl(c: whitebox.Context)(args: c.Expr[Any]*): c.Tree = {
    handleResult(c)(MacroInterpreter.setImpl(c)(args: _*), DslMode.Set)
  }

  def lensImpl(c: whitebox.Context)(args: c.Expr[Any]*): c.Tree = {
    handleResult(c)(MacroInterpreter.lensImpl(c)(args: _*), DslMode.Lens)
  }

  private def handleResult(c: whitebox.Context)(
    result: MacroResult[c.Type, c.Tree], mode: DslMode): c.Tree = {

    result match {
      case MacroResult(Right(tree), _) => tree
      case MacroResult(Left(err), infos) =>
        val errMsg = ErrorMessages.message(err, mode, infos)
        c.abort(c.enclosingPosition, errMsg)
    }
  }
} 
开发者ID:kenbot,项目名称:goggles,代码行数:34,代码来源:GogglesMacros.scala

示例7: Demixin

//设置package包名称以及导入依赖的类
package com.thoughtworks.feature
import shapeless._
import scala.language.experimental.macros
import scala.reflect.macros.whitebox


trait Demixin[ConjunctionType] {
  type Out <: HList
}

object Demixin {

  type Aux[ConjunctionType, Out0] = Demixin[ConjunctionType] {
    type Out = Out0
  }

  def apply[ConjunctionType](implicit demixin: Demixin[ConjunctionType]): Demixin.Aux[ConjunctionType, demixin.Out] =
    demixin

  implicit def materialize[ConjunctionType]: Demixin[ConjunctionType] =
    macro Macros.materialize[ConjunctionType]

  private[Demixin] final class Macros(val c: whitebox.Context) extends CaseClassMacros {
    import c.universe._

    private def demixin(t: Type): Stream[Type] = {
      t.dealias match {
        case RefinedType(superTypes, refinedScope) if refinedScope.isEmpty =>
          superTypes.toStream.flatMap(demixin)
        case any if definitions.AnyTpe <:< any =>
          Stream.empty[Type]
        case notRefinedType =>
          Stream(notRefinedType)
      }
    }

    def materialize[ConjunctionType: WeakTypeTag]: Tree = {
      val conjunctionType = weakTypeOf[ConjunctionType]
      val out = mkHListTpe(demixin(conjunctionType).distinct.toList)
      val result = q"""
        new _root_.com.thoughtworks.feature.Demixin[$conjunctionType] {
          type Out = $out
        } : _root_.com.thoughtworks.feature.Demixin.Aux[$conjunctionType, $out]
      """
//      c.info(c.enclosingPosition, showCode(result), true)
      result
    }
  }

} 
开发者ID:ThoughtWorksInc,项目名称:feature.scala,代码行数:51,代码来源:Demixin.scala

示例8: ActorFactoryMacros

//设置package包名称以及导入依赖的类
package org.imdex.tractor.meta

import org.imdex.tractor
import org.imdex.tractor.ActorConf

import scala.annotation.tailrec
import scala.reflect.macros.whitebox


private[tractor] class ActorFactoryMacros(val c: whitebox.Context) {
    import c.universe._

    def spawn[Messages : WeakTypeTag](conf: Expr[ActorConf[_]], args: Expr[Any]*): Tree = {
        val actualType = conf.actualType
        if (actualType.typeArgs.isEmpty) c.abort(c.enclosingPosition, s"Invalid actor type ${actualType.typeSymbol.fullName}")

        val `type` = actualType.typeArgs.head
        val argTypes = args.map(_.actualType)

        val constructors = `type`.decls.collect{ case decl if decl.isConstructor => decl.asMethod }

        @tailrec
        def check(args: Seq[Type], ctorArgs: List[Type]): Boolean = {
            if (args.isEmpty && ctorArgs.isEmpty)                                                true
            else if ((args.isEmpty && ctorArgs.nonEmpty) || (args.nonEmpty && ctorArgs.isEmpty)) false
            else {
                if (args.head weak_<:< ctorArgs.head) check(args.tail, ctorArgs.tail)
                else                                  false
            }
        }

        val constructor = constructors.find { ctor =>
            val args = ctor.paramLists.flatten.map(_.typeSignature) // TODO: optimize with lazy iteration
            check(argTypes, args)
        }.getOrElse(c.abort(c.enclosingPosition, "Suitable constructor not found"))

        val params = {
            val paramLists = constructor.paramLists

            import tractor.util._

            if (paramLists.tail.isEmpty) args :: Nil
            else                         (args: Seq[Expr[Any]]).split(paramLists.map(_.length): _*)
        }

        q"""val creator = new ActorInstanceCreator[${`type`}] {
            override def create: ${`type`} = new ${`type`}(...$params)
            override def conf = $conf.asInstanceOf[Conf[${`type`}]]
        }
        spawn[${weakTypeOf[Messages]}, ${`type`}](creator)"""
    }
} 
开发者ID:Im-dex,项目名称:trActor,代码行数:53,代码来源:ActorFactoryMacros.scala

示例9: Common

//设置package包名称以及导入依赖的类
package org.imdex.tractor.meta.union

import org.imdex.tractor.meta.Macros
import org.imdex.tractor.union.{Union, |, ?}

import scala.annotation.tailrec
import scala.collection.mutable
import scala.reflect.macros.whitebox


private[union] class Common[C <: whitebox.Context](val commonCtx: C) extends Macros(commonCtx) {
    import c.universe._

    private[this] val UnionType = typeOf[_ | _]
    private[this] val EmptyType = typeOf[?]

    def decay[T <: Union : c.WeakTypeTag]: Set[TypeWrapper] = decay(weakTypeOf[T])

    def decay(unionType: Type): Set[TypeWrapper] = {
        @tailrec
        def decay(types: List[Type], buffer: mutable.Builder[TypeWrapper, Set[TypeWrapper]] = Set.newBuilder[TypeWrapper]): Set[TypeWrapper] = {
            if (types.isEmpty) {
                buffer.result()
            } else {
                val tpe = types.head

                if (tpe =:= EmptyType)              decay(types.tail, buffer)
                else if (tpe.erasure =:= UnionType) decay(types.tail ++ tpe.dealias.typeArgs, buffer)
                else                                decay(types.tail, buffer += tpe)
            }
        }

        decay(unionType :: Nil)
    }
} 
开发者ID:Im-dex,项目名称:trActor,代码行数:36,代码来源:Common.scala

示例10: ContextMockSpec

//设置package包名称以及导入依赖的类
import macroni.{ContextMock, TreeSpec, CompileSpec}
import macroni.matcher._

import org.specs2.mock.Mockito
import scala.reflect.macros.{blackbox, whitebox}
import org.specs2.matcher._

class ContextMockSpec extends TreeSpec with ContextMock with CompileSpec {
  "blackbox context tree equals same tree" >> {
    val context = mockContext[blackbox.Context]
    import context.universe._

    val tree = q"val golum = true"
    tree should beEqualToTree(q"val golum = true")
  }

  "whitebox context tree equals same tree" >> {
    val context = mockContext[whitebox.Context]
    import context.universe._

    val tree = q"val golum = true"
    tree should beEqualToTree(q"val golum = true")
  }

  "mocked context with compile matcher" >> {
    val context = mockContext[whitebox.Context]
    import context.universe._

    q"1" must compile
  }
} 
开发者ID:cornerman,项目名称:macroni,代码行数:32,代码来源:ContextMockSpec.scala

示例11: extractWithName

//设置package包名称以及导入依赖的类
package com.github.cuzfrog.scmd.internal

import scala.language.experimental.macros

import scala.reflect.ClassTag
import scala.reflect.macros.whitebox


  def extractWithName[T: ClassTag](params: Seq[Term.Arg],
                                   paramName: String, pos: Position): Option[T] = {
    val value = params.map {
      case named: Term.Arg.Named => named
      case unnamed =>
        abort(pos, s"Definition must use named parameter in def for content:${unnamed.syntax}")
    }.collect { case Term.Arg.Named(Term.Name(n), v) if n == paramName => v }.headOption
    val tpe = implicitly[ClassTag[T]]

    val actual = tpe.runtimeClass match {
      case rc if rc == classOf[String] => value collect { case Lit.String(v) => v }
      case rc if rc == classOf[Boolean] => value collect { case Lit.Boolean(v) => v }
      case rc if rc == classOf[Term] => value collect { case term: Term => term }
      case rc if rc == classOf[Term.Arg] => value
      case rc => throw new AssertionError(s"Type not coded for argDef def: $rc")
    }
    actual.map(_.asInstanceOf[T])
  }
}

private object RawArgMacroImpl {
  def impl[T: c.WeakTypeTag](c: whitebox.Context)(params: c.Tree)(classTag: c.Tree, pos: c.Tree): c.Tree = {
    import c.universe._
    val termName = c.internal.enclosingOwner.asTerm.name.toString

    val tpe = c.weakTypeOf[T]
    val objectName = q"com.github.cuzfrog.scmd.internal.RawArgMacro"
    val tree = q"$objectName.extractWithName[$tpe]($params,$termName,$pos)"
    //println(showCode(tree))
    tree
  }
} 
开发者ID:cuzfrog,项目名称:simple-cmd,代码行数:41,代码来源:RawArgMacro.scala

示例12: Super

//设置package包名称以及导入依赖的类
package com.github.alexeyr.scaladry

import macrocompat.bundle

import scala.reflect.macros.whitebox

object Super {
  
  def superCallOf[T]: Any = macro SuperImpl.superCallOf[T]
}

@bundle
private class SuperImpl(val c: whitebox.Context) {
  import c.universe._

  def superCallOf[T: WeakTypeTag]: Tree = {
    c.internal.enclosingOwner match {
      case method: MethodSymbol =>
        if (method.overrides.isEmpty)
          c.abort(c.enclosingPosition, s"method ${method.name} overrides nothing, superCall makes no sense")
        val args = method.paramLists.map(_.map { sym =>
          val name = sym.asTerm.name.toTermName
          // check that the symbol is not shadowed (comparing positions because == on symbols can produce false
          // negative in this case)
          if (sym.pos == c.typecheck(q"$name").symbol.pos)
            name
          else {
            c.abort(c.enclosingPosition, s"superCall is not allowed because parameter $name is shadowed")
          }
        })
        val typeOfT = weakTypeOf[T]
        val typeParams = method.typeParams.map(_.asType.name)
        if (typeOfT =:= typeOf[Nothing])
          q"super.${method.name.toTermName}[..$typeParams](...$args)"
        else
          q"super[${typeOfT.typeSymbol.name.toTypeName}].${method.name.toTermName}[..$typeParams](...$args)"
      case _ =>
        c.abort(c.enclosingPosition, "superCall must be contained in a method")
    }
  }
} 
开发者ID:alexeyr,项目名称:scala-dry,代码行数:42,代码来源:Super.scala

示例13: ShowRenderMacros

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

import scala.reflect.macros.whitebox
import scala.util.Try

class ShowRenderMacros(val c: whitebox.Context) {
  import c.universe.{Try => TryTree, _}

  private def html(tree: Tree) = Try(c.typecheck(tree)).flatMap {
    checked => Try(c.typecheck(q"vegas.render.ShowHTML($checked)"))
  }

  def materializeDefault: Tree = {
    val possibilities: Try[Tree] =
      html(q"""(str: String) => { println(org.apache.zeppelin.spark.utils.DisplayUtils.html(str)) }""") orElse
      html(q"""(str: String) => { publish.html(str) }""") orElse
      html(q"""(str: String) => { display.html(str) }""") orElse
      html(q"""(str: String) => { kernel.display.content("text/html", str) }""") orElse
      Try(c.typecheck(q"""vegas.render.ShowRender.using(_.window.show)"""))

    possibilities.getOrElse(c.abort(c.enclosingPosition, "No default Vegas renderer could be materialized"))
  }
} 
开发者ID:vegas-viz,项目名称:Vegas,代码行数:24,代码来源:ShowRenderMacros.scala

示例14: Macrowave

//设置package包名称以及导入依赖的类
package com.github.zenpie.macrowave.internal

import java.util.LinkedList

import com.github.zenpie.macrowave.internal.scanner.FiniteAutomaton
import com.github.zenpie.macrowave.internal.parser.{RuleValidation, SetComputation, SymbolString}

import scala.reflect.macros.whitebox

class Macrowave(val c: whitebox.Context) extends AnyRef
  with MacroUtils
  with scanner.RuleParser
  with parser.RuleParser {

  import c.universe._

  def transformGrammars(annottees: Tree*): c.Tree = {
    val typedAnnottees = annottees map (c.typecheck(_, silent = false))

    val grammars = typedAnnottees map {
      case tree @ q"""$mods class $cname(...$ctors) extends $superclasses { ..$stms }""" =>
        val grammar = new Grammar(c)
        val stmList = new LinkedList[Tree]()
        stms.foreach(stm => stmList.add(stm))

        scannerRulesFromStatements(grammar, stmList)
        parserRulesFromStatements(grammar, stmList)
        RuleValidation.validateParserRules(grammar)
        val dfa = FiniteAutomaton.generate(grammar)

        SymbolString.fromGrammar(grammar)
        SetComputation.calculateFirstAndFollowSets(grammar)

        q"""$mods class $cname(...$ctors) extends $superclasses {}"""
      case x =>
        c.abort(x.pos, "Element annotated with 'grammar' is no Grammar!")
    }

    q"{..$grammars}"
  }

} 
开发者ID:zen-pie,项目名称:macrowave,代码行数:43,代码来源:Macrowave.scala

示例15: isRuleTpe

//设置package包名称以及导入依赖的类
package com.github.zenpie.macrowave.internal

import scala.reflect.macros.whitebox

private[internal] trait MacroUtils {
  val c: whitebox.Context
  import c.universe._

  private[internal] val RegExpTpe = typeOf[com.github.zenpie.macrowave.RegExp]
  private[internal] val TokenTpe = typeOf[com.github.zenpie.macrowave.Token]
  private[internal] val StartTpe = typeOf[com.github.zenpie.macrowave.start]
  private[internal] val WhiteSpaceTpe = typeOf[com.github.zenpie.macrowave.whiteSpace]
  private[internal] val SingletonRuleTpe = typeOf[com.github.zenpie.macrowave.Rule[
    com.github.zenpie.macrowave.::[String, com.github.zenpie.macrowave.HNil]]]

  private[internal] val RuleTpe = typeOf[com.github.zenpie.macrowave.Rule[_]]
  private[internal] val Rule1Tpe = typeOf[com.github.zenpie.macrowave.Rule1[_]]

  private[internal] val validRuleActions = ((0 to 22) map (n => s"RuleAction$n")).toSet

  private[internal] def isRuleTpe(tree: Tree): Boolean =
    if (!tree.isType) false else {
      val tpe = tree.tpe
      val tpeArgs = tpe.typeArgs

      val apRule = appliedType(RuleTpe, tpeArgs)
      val apRule1 = appliedType(Rule1Tpe, tpeArgs)

      val isRule = tpe <:< apRule
      val isRule1 = tpe <:< apRule1

      isRule || isRule1
    }

  private[internal] def isMacrowavePackageObj(prefix: Tree): Boolean =
    prefix match {
      case Select(Select(Select(Select(Ident(TermName("com")), TermName("github")), TermName("zenpie")), TermName("macrowave")), TermName("package")) => true
      case Select(Select(Select(Ident(TermName("com")), TermName("github")), TermName("zenpie")), TermName("macrowave")) => true
      case Select(Select(This(TypeName("zenpie")), TermName("macrowave")), TermName("package")) => true
      case Select(This(TypeName("macrowave")), TermName("package")) => true
      case This(TypeName("macrowave")) => true
      case _ => false
    }

  private[internal] def isScalaPredef(prefix: Tree): Boolean =
    prefix match {
      case Select(This(TypeName("scala")), TermName("Predef")) => true
      case _ => false
    }

  private[internal] def hasAnnotation(tree: Tree, annotation: Type): Boolean =
    tree.symbol.annotations.exists(_.tree.tpe =:= annotation)

} 
开发者ID:zen-pie,项目名称:macrowave,代码行数:55,代码来源:MacroUtils.scala


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