scala.reflect.runtime.currentMirror Scala Examples

The following examples show how to use scala.reflect.runtime.currentMirror. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: RefineMacroBenchmark.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.benchmark

import org.openjdk.jmh.annotations._
import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox

@BenchmarkMode(Array(Mode.AverageTime))
@State(Scope.Thread)
class RefineMacroBenchmark {
  private val toolBox =
    currentMirror.mkToolBox()

  private val autoRefineV_PosInt_tree =
    toolBox.parse("""
      import eu.timepit.refined.auto.autoRefineV
      import eu.timepit.refined.types.numeric.PosInt
      val x: PosInt = 1
      """)

  @Benchmark
  def autoRefineV_PosInt: Any =
    toolBox.eval(autoRefineV_PosInt_tree)
} 
Example 2
Source File: InferMacroBenchmark.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.benchmark

import org.openjdk.jmh.annotations._
import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox

@BenchmarkMode(Array(Mode.AverageTime))
@State(Scope.Thread)
class InferMacroBenchmark {
  private val toolBox =
    currentMirror.mkToolBox()

  private val autoInfer_Greater_tree =
    toolBox.parse("""
      import eu.timepit.refined.W
      import eu.timepit.refined.api.Refined
      import eu.timepit.refined.auto.autoInfer
      import eu.timepit.refined.numeric.Greater
      val a: Int Refined Greater[W.`5`.T] = Refined.unsafeApply(10)
      val b: Int Refined Greater[W.`0`.T] = a
      """)

  @Benchmark
  def autoInfer_Greater: Any =
    toolBox.eval(autoInfer_Greater_tree)
} 
Example 3
Source File: eval.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined

import eu.timepit.refined.api.Validate
import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox
import shapeless.Witness

object eval {

  
  final case class Eval[S](s: S)

  object Eval {
    // Cache ToolBox for Eval Validate instances
    private lazy val toolBox = currentMirror.mkToolBox()

    implicit def evalValidate[T, S <: String](
        implicit mt: Manifest[T],
        ws: Witness.Aux[S]
    ): Validate.Plain[T, Eval[S]] = {
      // The ascription (T => Boolean) allows to omit the parameter
      // type in ws.value (i.e. "x => ..." instead of "(x: T) => ...").
      val tree = toolBox.parse(s"(${ws.value}): ($mt => Boolean)")

      val predicate = toolBox.eval(tree).asInstanceOf[T => Boolean]
      Validate.fromPredicate(predicate, _ => ws.value, Eval(ws.value))
    }
  }
} 
Example 4
Source File: RecordSchemaGenerator.scala    From avrohugger   with Apache License 2.0 5 votes vote down vote up
package avrohugger
package input
package reflectivecompilation
package schemagen

import parsers.ScalaDocParser
import stores.{ SchemaStore, TypecheckDependencyStore }

import org.apache.avro.Schema.Field
import org.apache.avro.Schema

import java.util.{ Arrays => JArrays }

import scala.reflect.runtime.universe._
import scala.reflect.runtime.currentMirror
import scala.collection.JavaConverters._

object RecordSchemaGenerator  {

  def generateSchema(
    className: String, 
    namespace: Option[Name], 
    fields: List[ValDef],
    maybeScalaDoc: Option[String],
    schemaStore: SchemaStore, 
    typecheckDependencyStore: TypecheckDependencyStore): Schema = {

    // Can't seem to typecheck packaged classes, so splice-in unpackaged versions
    // and later the FieldSchemaGenerator's type matcher must be passed the field's 
    // namespace explicitly.
    def typeCheck(t: Tree) = {
      val dependencies = typecheckDependencyStore.knownClasses.values.toList
      Toolbox.toolBox.typeCheck(q"..$dependencies; {type T = $t}") match {
	      case x @ Block(classDefs, Block(List(TypeDef(mods, name, tparams, rhs)), const)) => rhs.tpe
        case _ => t.tpe // if there are no fields, then no dependencies either
      }
    }

    def toAvroFieldSchema(valDef: ValDef) = {
      val (referredNamespace, fieldType) = valDef.tpt match {
        case tq"$ns.$typeName" => (Some(newTermName(ns.toString)), tq"$typeName")
        case t => (namespace, t)
      }

      val maybeFieldDoc = ScalaDocParser.fieldDocsMap(maybeScalaDoc).get(valDef.name.toString)

      new FieldSchemaGenerator().toAvroField(
        referredNamespace,
        valDef.name, 
        typeCheck(fieldType),
        valDef.rhs,
        maybeFieldDoc,
        schemaStore
      )
    }

    // conversion from Option to String/null is for compatibility with Apache Avro
    val ns = namespace match {
      case Some(n) => n.toString
      case None => null
    }

    val avroFields = fields.map(valDef => {
      toAvroFieldSchema(valDef)
    })

    // conversion from Option to String/null is for compatibility with Apache Avro
    val recordDoc = ScalaDocParser.getTopLevelDoc(maybeScalaDoc)

    val avroSchema = Schema.createRecord(className, recordDoc, ns, false)    
    avroSchema.setFields(JArrays.asList(avroFields.toArray:_*))
    schemaStore.accept(avroSchema)
    avroSchema
  }

} 
Example 5
Source File: ContractProxyModule.scala    From fintrospect   with Apache License 2.0 5 votes vote down vote up
package io.fintrospect

import com.twitter.finagle.Service
import com.twitter.finagle.http.path.{Path, Root}
import com.twitter.finagle.http.{Request, Response}
import io.fintrospect.renderers.swagger2dot0.{ApiInfo, Swagger2dot0Json}


import scala.reflect.runtime.universe.TypeTag
import scala.reflect.runtime.{currentMirror, universe}



object ContractProxyModule {
  def apply[T <: Contract](name: String, service: Service[Request, Response], contract: T, rootPath: Path = Root, description: String = null)(implicit tag: TypeTag[T]): RouteModule[Request, Response] = {
    val descriptionOption = Option(description).getOrElse(s"Proxy services for $name API")
    val routes = universe.typeOf[T].members
      .filter(_.isModule)
      .map(_.asModule)
      .map(currentMirror.reflectModule(_).instance)
      .filter(_.isInstanceOf[ContractEndpoint])
      .map(_.asInstanceOf[ContractEndpoint].route)

    routes.foldLeft(RouteModule(rootPath, Swagger2dot0Json(ApiInfo(name, name, descriptionOption)))) {
      (spec, route) => spec.withRoute(route.bindToProxy(service))
    }
  }
} 
Example 6
Source File: Traverser.scala    From scaldy   with Apache License 2.0 5 votes vote down vote up
package com.paytrue.scaldy

import java.nio.charset.StandardCharsets
import java.nio.file.Path
import scala.io.Source
import scala.reflect.runtime.currentMirror
import scala.reflect.runtime.universe.Flag._
import scala.reflect.runtime.universe._
import scala.tools.reflect.ToolBox

class ClassDefTraverser(file: Path) extends Traverser {
  var classes: List[BeanClass] = List.empty

  override def traverse(tree: Tree) = {
    tree match {
      case ClassDef(mods, name, _, impl) ⇒
        val valTraverser = new ValDefTraverser
        valTraverser.traverse(tree)
        val parents = impl.parents.map(_.toString())
        classes = classes :+ BeanClass(name.toString, valTraverser.properties, parents,
          isAbstract = mods.hasFlag(ABSTRACT), isTrait = mods.hasFlag(TRAIT), sourceFile = file)

      case _ ⇒
    }
    super.traverse(tree)
  }
}

class ValDefTraverser extends Traverser {
  var properties: List[Property] = List.empty

  override def traverse(tree: Tree) = {
    tree match {
      case ValDef(Modifiers(_, _, annotations), valName, tpt, _) if hasBeanProperty(annotations) ⇒
        val isRequired = hasRequired(annotations)
        tpt match {
          case AppliedTypeTree(Select(qualifier, typeName), args) ⇒
            val typeTraverser = new TypeArgsTraverser
            typeTraverser.traverseTrees(args)
            properties :+= Property(valName.toString, tpt.toString(), typeTraverser.refTypes, isRequired)

          case _ ⇒
            properties :+= Property(valName.toString, tpt.toString(), Set.empty, isRequired)
        }

      case _ ⇒
    }
    super.traverse(tree)
  }

  private def hasBeanProperty(annotations: List[Tree]) = annotations.exists {
    case Apply(Select(New(Ident(TypeName("BeanProperty"))), _), _) ⇒ true
    case _ ⇒ false
  }

  private def hasRequired(annotations: List[Tree]) = annotations.exists {
    case Apply(Select(New(Annotated(_, Ident(TypeName("Required")))), _), _) ⇒ true
    case _ ⇒ false
  }
}

class TypeArgsTraverser extends Traverser {
  var refTypes: Set[String] = Set.empty

  override def traverse(tree: Tree) = {
    tree match {
      case ident @ Ident(identName) if ident.isType ⇒
        refTypes += identName.toString
      case _ ⇒
    }
    super.traverse(tree)
  }
}

object FileClassFinder {
  def getClassesFromFile(file: Path): List[BeanClass] = {
    val toolbox = currentMirror.mkToolBox()
    val fileContents = Source.fromFile(file.toString, StandardCharsets.UTF_8.name()).getLines().drop(1).mkString("\n")
    val tree = toolbox.parse(fileContents)
    val traverser = new ClassDefTraverser(file)
    traverser.traverse(tree)
    traverser.classes
  }
} 
Example 7
Source File: Analyser.scala    From Raphtory   with Apache License 2.0 5 votes vote down vote up
package com.raphtory.core.analysis.API

import akka.actor.ActorContext
import com.raphtory.core.analysis.API.GraphLenses.GraphLens

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.io.Source
import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox
case class ManagerCount(count: Int)
case class WorkerID(ID: Int)

class BlankAnalyser(args:Array[String]) extends Analyser(args) {
  override def analyse(): Unit = {}
  override def setup(): Unit = {}
  override def returnResults(): Any = {}
  override def defineMaxSteps(): Int = 1
  override def processResults(results: ArrayBuffer[Any], timeStamp: Long, viewCompleteTime: Long): Unit = {println("howdy!")}
}


case class LoadExternalAnalyser(rawFile: String,args:Array[String]) {
  private val toolbox = currentMirror.mkToolBox()
  private val tree = toolbox.parse(rawFile)
  private val compiledCode = toolbox.compile(tree).apply().asInstanceOf[Class[Analyser]]
  def newAnalyser = compiledCode.getConstructor(classOf[Array[String]]).newInstance(args).asInstanceOf[Analyser]
}

abstract class Analyser(args:Array[String]) extends java.io.Serializable {
  implicit var context: ActorContext      = null
  implicit var managerCount: ManagerCount = null
  implicit var proxy: GraphLens            = null
  var workerID: Int                       = 0

  private var toPublish:mutable.ArrayBuffer[String] = ArrayBuffer()
  final def sysSetup(context: ActorContext, managerCount: ManagerCount, proxy: GraphLens, ID: Int) = {
    this.context = context
    this.managerCount = managerCount
    this.proxy = proxy
    this.workerID = ID
  }

  def publishData(data:String) = toPublish +=data
  def getPublishedData() = toPublish.toArray
  def clearPublishedData() =  toPublish = ArrayBuffer()

  def analyse(): Unit
  def setup(): Unit
  def returnResults(): Any

  def defineMaxSteps(): Int
  def processResults(results: ArrayBuffer[Any], timeStamp: Long, viewCompleteTime: Long): Unit
  def processViewResults(results: ArrayBuffer[Any], timestamp: Long, viewCompleteTime: Long): Unit =
    processResults(results, timestamp: Long, viewCompleteTime: Long)
  def processWindowResults(results: ArrayBuffer[Any], timestamp: Long, windowSize: Long, viewCompleteTime: Long): Unit =
    processResults(results, timestamp: Long, viewCompleteTime: Long)
  def processBatchWindowResults(
      results: ArrayBuffer[Any],
      timestamp: Long,
      windowSet: Array[Long],
      viewCompleteTime: Long
  ): Unit = processResults(results, timestamp: Long, viewCompleteTime: Long)
} 
Example 8
Source File: ASTMatchers.scala    From Argus   with MIT License 5 votes vote down vote up
package argus.macros

import org.scalactic.Equality
import org.scalatest.matchers.{ MatchResult, Matcher }
import scala.tools.reflect.ToolBox


trait ASTMatchers {

  val runtimeUniverse = scala.reflect.runtime.universe
  import runtimeUniverse._
  import scala.reflect.runtime.currentMirror
  val toolbox = currentMirror.mkToolBox()

  // For testing equality between trees in tests
  implicit val treeEq = new Equality[Tree] {
    def areEqual(a: Tree, b: Any): Boolean =
      b match {
        // equalsStructure bug: https://github.com/scalamacros/paradise/issues/80
        case c: Tree => showRaw(a) == showRaw(c) //.equalsStructure(c)
        case _ => false
      }
  }

  implicit val valDefEq = new Equality[ValDef] {
    def areEqual(a: ValDef, b: Any): Boolean =
      b match {
        case c: ValDef => showRaw(a) == showRaw(c)
        case _ => false
      }
  }

  implicit val listTreeEq = new Equality[List[Tree]] {
    def areEqual(a: List[Tree], b: Any): Boolean =
      b match {
        case c: List[_] => a.size == c.size && a.zip(c).forall { case(x,y) => treeEq.areEqual(x,y) }
        case _ => false
      }
  }

  val extractCodecNameAndType: PartialFunction[Tree, (String, String)] = {
    case q"implicit val $name: $typ = $_" => (name.toString, typ.toString)
  }

} 
Example 9
Source File: ObjectUtil.scala    From vamp   with Apache License 2.0 5 votes vote down vote up
package io.vamp.common.util

import org.json4s.{ Extraction, Formats }

import scala.collection.JavaConverters._
import scala.reflect.runtime.currentMirror
import scala.reflect.runtime.universe._

object ObjectUtil {

  def isPrimitive(any: Any) = any match {
    case _: Boolean ⇒ true
    case _: Byte    ⇒ true
    case _: Char    ⇒ true
    case _: Short   ⇒ true
    case _: Int     ⇒ true
    case _: Long    ⇒ true
    case _: Float   ⇒ true
    case _: Double  ⇒ true
    case _: String  ⇒ true
    case _          ⇒ false
  }

  def unwrap: Any ⇒ Any = {
    case p if isPrimitive(p)  ⇒ p
    case e: Enumeration#Value ⇒ e
    case l: List[_]           ⇒ l.map(unwrap)
    case m: Map[_, _]         ⇒ m.map { case (k, v) ⇒ k → unwrap(v) }
    case null                 ⇒ None
    case Some(s)              ⇒ Option(unwrap(s))
    case None                 ⇒ None
    case any ⇒
      val reflection = currentMirror.reflect(any)
      currentMirror.reflect(any).symbol.typeSignature.members.toList
        .collect { case s: TermSymbol if !s.isMethod ⇒ reflection.reflectField(s) }
        .map(r ⇒ r.symbol.name.toString.trim → unwrap(r.get))
        .toMap
  }

  def asJava: Any ⇒ Any = {
    case l: List[_]   ⇒ l.map(asJava).asJava
    case m: Map[_, _] ⇒ m.map({ case (k, v) ⇒ k → asJava(v) }).asJava
    case Some(s)      ⇒ Option(asJava(s))
    case any          ⇒ any
  }

  def asScala: Any ⇒ AnyRef = {
    case value: java.util.Map[_, _]   ⇒ value.asScala.map({ case (k, v) ⇒ k → asScala(v) }).toMap
    case value: java.util.List[_]     ⇒ value.asScala.map(asScala).toList
    case value: java.lang.Iterable[_] ⇒ value.asScala.map(asScala).toList
    case value: java.util.Optional[_] ⇒ if (value.isPresent) Option(asScala(value.get)) else None
    case value                        ⇒ value.asInstanceOf[AnyRef]
  }

  def merge(maps: Map[String, Any]*)(implicit formats: Formats): Map[String, AnyRef] = {
    maps.tail.foldLeft(Extraction.decompose(maps.head)) {
      (op1, op2) ⇒ op1 merge Extraction.decompose(op2)
    }.extract[Map[String, AnyRef]]
  }
}