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


Scala macros类代码示例

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


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

示例1: DSLFeature

//设置package包名称以及导入依赖的类
package org.scala_lang.virtualized

import scala.reflect.macros.blackbox.Context
import language.experimental.macros
import scala.util.matching.Regex

trait MacroModule {
  type Ctx <: Context
  val c: Ctx
}

trait DataDefs extends MacroModule {
  import c.universe._
  case class DSLFeature(tpe: Option[Type], name: String, targs: List[Tree], args: List[List[Type]])
}


  def className: String = ???
  lazy val typeRegex = new Regex("(" + className.replace("$", "\\$") + """\.this\.)(\w*)""")
  lazy val typetagRegex = new Regex("""(scala\.reflect\.runtime\.[a-zA-Z`]*\.universe\.typeTag\[)(\w*)\]""")
  def code(tree: Tree, shortenDSLNames: Boolean = true): String = {
    var short = showCode(tree)
    if (shortenDSLNames) {
      typeRegex findAllIn short foreach { m =>
        val typeRegex(start, typ) = m
        short = short.replace(start + typ, typ.toUpperCase())
      }
      typetagRegex findAllIn short foreach { m =>
        val typetagRegex(start, typ) = m
        short = short.replace(start + typ + "]", "TYPETAG[" + typ.toUpperCase() + "]")
      }
    }
    short
  }
} 
开发者ID:GeorgOfenbeck,项目名称:websiteSpiralS,代码行数:36,代码来源:Utils.scala

示例2: Virtualizer

//设置package包名称以及导入依赖的类
package org.scala_lang.virtualized

import language.experimental.macros
import scala.annotation.StaticAnnotation
import scala.reflect.macros.blackbox.Context


    val expandees = annottee match {
      case Some(a) => transformer.virtualize(a)._1 :: rest
      case None    => rest
    }

    c.Expr(Block(expandees, Literal(Constant(()))))
  }

  private final class Virtualizer[C <: Context](val c: C)
    extends LanguageVirtualization {
    type Ctx = C
    val debugLevel = 0
  }
} 
开发者ID:GeorgOfenbeck,项目名称:websiteSpiralS,代码行数:22,代码来源:Virtualize.scala

示例3: SealedTraitValues

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

import language.experimental.macros
import scala.reflect.macros.blackbox


object SealedTraitValues {
  def values[A]: Set[A] = macro values_impl[A]

  def values_impl[A: c.WeakTypeTag](c: blackbox.Context) = {
    import c.universe._

    val symbol = weakTypeOf[A].typeSymbol

    def isSubtype(candidate: Symbol): Boolean = {
      candidate == symbol || candidate.typeSignature.baseClasses.drop(1).exists(isSubtype)
    }

    if (!symbol.isClass) c.abort(
      c.enclosingPosition,
      "Can only enumerate values of a sealed trait or class."
    ) else if (!symbol.asClass.isSealed) c.abort(
      c.enclosingPosition,
      "Can only enumerate values of a sealed trait or class."
    ) else {
      // check all sibling declarations for subtypes
      val siblingSubclasses: List[Symbol] = scala.util.Try {
        c.internal.enclosingOwner.owner.typeSignature.decls
          .filter(a => a.isClass || a.isModule || a.isModuleClass)
          .filter(isSubtype).toList
      } getOrElse Nil

      // create a list of all known subtypes
      val subclasses = symbol.asClass.knownDirectSubclasses.toList ::: siblingSubclasses

      // filter traits and abstract classes out of the candidates list
      val candidates = subclasses.filterNot(a => a.isClass && (a.asClass.isTrait || a.asClass.isAbstract))

      if (!candidates.forall(x => x.isModuleClass || x.isModule)) c.abort(
        c.enclosingPosition,
        "All children must be objects."
      ) else c.Expr[Set[A]] {
        def sourceModuleRef(sym: Symbol) = Ident(
          if (sym.isModule) sym else
            sym.asInstanceOf[
              scala.reflect.internal.Symbols#Symbol
              ].sourceModule.asInstanceOf[Symbol]
        )

        Apply(
          Select(
            reify(Set).tree,
            TermName("apply")
          ),
          candidates.map(sourceModuleRef(_))
        )
      }
    }
  }
} 
开发者ID:nrf110,项目名称:scala-common,代码行数:61,代码来源:SealedTraitValues.scala

示例4: LoadFile

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

import java.io.{BufferedInputStream, FileInputStream}
import java.nio.file.{Files, Paths}

import language.experimental.macros
import scala.reflect.macros.blackbox.Context
import scala.io.Source
import org.apache.commons.codec.binary.Base64
import org.apache.commons.io.IOUtils

object LoadFile {
  def syncLoad(fileName: String): String = macro syncLoadImpl

  def syncLoadImpl(c: Context)(fileName: c.Expr[String]): c.Expr[String] = {
    import c.universe._
    val Literal(Constant(fileNameStr)) = fileName.tree
    val fileContents = Source.fromFile("./server/public/" + fileNameStr).getLines.mkString("\n")
    c.Expr[String](Literal(Constant(fileContents)))
  }

  def toBase64(fileName: String): String = macro toBase64Impl

  def toBase64Impl(c: Context)(fileName: c.Expr[String]): c.Expr[String] = {
    import c.universe._
    val Literal(Constant(fileNameStr)) = fileName.tree
    return c.Expr[String](Literal(Constant(new String(""))))
    //val bis = new BufferedInputStream(new FileInputStream("./server/public/" + fileNameStr))
    // Get byte array for base64 encoding
    //val fileBytes = Stream.continually(bis.read).takeWhile(-1 != _).map(_.toByte).toArray
    //val fileBytes = IOUtils.toByteArray(bis)
    val fileBytes = Files.readAllBytes(Paths.get("./server/public/" + fileNameStr))
    c.Expr[String](Literal(Constant(new String(Base64.encodeBase64(fileBytes)))))
  }
} 
开发者ID:gvatn,项目名称:play-scalajs-webgl-spark,代码行数:36,代码来源:LoadFile.scala

示例5: Port

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

import scalaz.\/
import scalaz.syntax.either._
import language.experimental.macros
import scala.reflect.macros.blackbox

final class Port private(val value: Int) extends AnyVal

object Port {
  def parse(p: Int): String \/ Port =
    if (1024 <= p && p < 65536) new Port(p).right
    else s"$p is out of range".left


  def apply(i: Int): Port = macro impl

  def impl(c: blackbox.Context)(i: c.Tree) = {
    import c.universe._

    def fail(s: String) = {
      val pos = c.enclosingPosition
      c.abort(pos.withPoint(pos.point + 1), s)
    }

    i match {
      case Literal(Constant(p: Int)) =>
        Port.parse(p) valueOr fail

        q"""
           _root_.msc.Port.parse($p) valueOr _root_.scala.sys.error
         """
      case other =>
        fail(other + " is not an Int literal. Use Port.parse instead.")
    }
  }
} 
开发者ID:mjhopkins,项目名称:macro-smart-constructors,代码行数:38,代码来源:Port.scala


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