本文整理汇总了Scala中scala.tools.reflect.ToolBox类的典型用法代码示例。如果您正苦于以下问题:Scala ToolBox类的具体用法?Scala ToolBox怎么用?Scala ToolBox使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ToolBox类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: Compiler
//设置package包名称以及导入依赖的类
package knot.msgpack.gen
object Compiler {
import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox
type CompiledExpr = () => Any
private[this] val _compiler = {
currentMirror.mkToolBox()
}
def compile(code: String): CompiledExpr = {
val tree = _compiler.parse(code)
_compiler.compile(tree)
}
def eval(code: String): Any = {
compile(code)()
}
def evalAs[T](code: String): T = {
eval(code).asInstanceOf[T]
}
}
示例2: RuntimeCompilationTest
//设置package包名称以及导入依赖的类
package com.github.cuzfrog.webdriver
import scala.reflect.runtime.universe
import scala.tools.reflect.ToolBox
private object RuntimeCompilationTest{
val tb = universe.runtimeMirror(getClass.getClassLoader).mkToolBox()
val classDef = tb.parse {
"""
|private class MyParser extends Function[String,String]{
| override def apply(v1: String): String = v1 + "123"
|}
|
|scala.reflect.classTag[MyParser].runtimeClass
""".stripMargin
}
val clazz = tb.compile(classDef).apply().asInstanceOf[Class[Function[String,String]]]
val instance = clazz.getConstructor().newInstance()
println(instance.apply("asdf"))
}
示例3: Main
//设置package包名称以及导入依赖的类
package game_of_life
import game_of_life.controller.GameController
import game_of_life.model.Game
import game_of_life.model.Game.SetupPredicate
import scala.io.StdIn
import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox
object Main extends App {
val controller = new GameController(
Game(rows = args(0).toInt, columns = args(1).toInt) {
args drop 2 match {
case Array() => Game.randomInit
case Array(word) if word equalsIgnoreCase "blinkers" => (row, column) => row % 4 == 1 && column % 4 < 3
case array => eval[SetupPredicate]("($r: Int, $c: Int) => { " + (array mkString " ") + " }: Boolean")
}
}
)()
do {
controller toggle ()
} while ((StdIn readLine ()) != null)
controller stop ()
private def eval[A](string: String): A = {
val tb = currentMirror mkToolBox ()
val tree = tb parse string
(tb eval tree).asInstanceOf[A]
}
}
示例4: ScalaToolboxInterpreter
//设置package包名称以及导入依赖的类
package com.outr.uberterm.interpreter
import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox
class ScalaToolboxInterpreter {
private lazy val toolbox = currentMirror.mkToolBox()
object eval {
def apply(code: String): Any = toolbox.eval(toolbox.parse(code))
def typed[T](code: String): T = apply(code).asInstanceOf[T]
}
object compile {
def apply(code: String): () => Any = toolbox.compile(toolbox.parse(code))
def typed[T](code: String): () => T = apply(code).asInstanceOf[() => T]
}
}
示例5: RuntimeCompiler
//设置package包名称以及导入依赖的类
package com.github.cuzfrog.webdriver
import scala.reflect.runtime.{universe => ru}
import scala.tools.reflect.ToolBox
private object RuntimeCompiler extends Logging {
private val tb = ru.runtimeMirror(getClass.getClassLoader).mkToolBox()
private def classDef(src: String) = {
logger.trace(s"Compile script.... md5 [${MD5(src)}]")
tb.parse(src)
}
def compileLogic(src: String): Function[String, _] = try {
val instance = tb.eval(classDef(src))
instance.asInstanceOf[Function1[String, _]]
} catch {
case e: Throwable =>
e.printStackTrace()
throw ScalaReflectionException("Runtime compilation failed.")
}
}
示例6: CompilerTree
//设置package包名称以及导入依赖的类
package org.ucf.spark.ScalaAST
import scala.tools.nsc._
import io._
import scala.io.Source
import scala.reflect.runtime.{universe =>ru}
import scala.tools.reflect.ToolBox
import com.google.common.io.Files
import java.nio.charset.Charset
import java.io.File
import scala.reflect.internal.util.BatchSourceFile
object CompilerTree extends Global(new Settings()){
new Run
def parseToTree(path:String) = {
val code = AbstractFile.getFile(path)
val bfs = new BatchSourceFile(code,code.toCharArray)
val parser = new syntaxAnalyzer.UnitParser(new CompilationUnit(bfs))
parser.smartParse()
}
def parseToString(path:String) = {
showRaw(this.parseToTree(path))
}
def parseWithMirror(path:String) = {
val source = Files.toString(new File(path),Charset.forName("UTF-8"))
val toolBox = ru.runtimeMirror(getClass.getClassLoader).mkToolBox()
toolBox.parse(source)
}
def parseWithMirrorTypeCheck(path:String) = {
val source = Files.toString(new File(path),Charset.forName("UTF-8"))
val toolBox = ru.runtimeMirror(getClass.getClassLoader).mkToolBox()
toolBox.typecheck(toolBox.parse(source))
}
}
示例7: TestUtils
//设置package包名称以及导入依赖的类
package utils
import java.io.File
import java.net.URLClassLoader
import helpers.Utils
import org.scalatest.{FlatSpec, Matchers}
import scala.reflect.runtime.{universe => ru}
import scala.tools.reflect.{ToolBox, ToolBoxError};
object TestUtils extends FlatSpec with Matchers {
val cl = getClass.getClassLoader.asInstanceOf[URLClassLoader]
val cp = cl.getURLs.map(_.getFile).mkString(File.pathSeparator)
val pluginPath = cp
val mirror = ru.runtimeMirror(cl)
val tb = mirror.mkToolBox(options = s"-Dmsg=hello -cp $cp -Xplugin:$cp") // TODO: Might have to extract plugin path instead of passing in all class paths
def expectMutability(klassesToImmutability: Map[List[String], String])(code: String): Unit = {
for ((klasses, immutabilityMessage) <- klassesToImmutability) {
expectMutability(klasses, immutabilityMessage)(code)
}
}
def expectMutability(klasses: List[String], immutabilityMessage: String)(code: String) {
for (klass <- klasses) {
expectMutability(klass, immutabilityMessage)(code)
}
}
def expectMutability(klass: String, immutabilityMessage: String)(code: String) {
val mutabilityMessage = Utils.mutabilityMessage(klass, immutabilityMessage)
Utils.setCurrentTestMessage(mutabilityMessage)
val e = intercept[ToolBoxError] {
// Intercept a false negative error to notify that the test was successful
tb.eval(tb.parse(code))
}
e.getMessage should include(mutabilityMessage)
}
}
示例8: RuntimeCompiler
//设置package包名称以及导入依赖的类
package com.github.cuzfrog.macros
import scala.reflect.runtime.{universe => ru}
import scala.tools.reflect.ToolBox
object RuntimeCompiler {
private val tb = ru.runtimeMirror(getClass.getClassLoader).mkToolBox()
private def classDef(src: String) = {
println("Parse logic class source for compilation:")
println(src)
tb.parse(src)
}
def compileLogic(src: String): Function[String, _] = {
val instance = tb.eval(classDef(src))
instance.asInstanceOf[Function1[String, _]]
}
private def getType[T: ru.TypeTag](instance: T): ru.Type = ru.typeOf[T]
}
示例9: CompileAs
//设置package包名称以及导入依赖的类
package mco.config
import scala.reflect.runtime._
import scala.reflect.runtime.universe.TypeTag
import scala.tools.reflect.ToolBox
import scala.util.Try
import scala.util.control.NonFatal
import mco.io.Fail
object CompileAs {
def apply[A: TypeTag](fullName: String): Try[A] = {
val toolbox = currentMirror.mkToolBox()
Try {
require(fullName matches "^[0-9a-zA-Z\\.]*$", s"Invalid name: $fullName")
s"$fullName: ${implicitly[TypeTag[A]].tpe}"
} map toolbox.parse map toolbox.compile recover {
case NonFatal(_) => throw Fail.MissingResource(fullName)
} map (eval => eval().asInstanceOf[A])
}
}
示例10: ReflectParser
//设置package包名称以及导入依赖的类
package at.vizu.s2n.parser
import at.vizu.s2n.log.Profiler._
import com.typesafe.scalalogging.LazyLogging
import scala.reflect.api.JavaUniverse
import scala.reflect.runtime.universe._
import scala.tools.reflect.ToolBox
class ReflectParser extends Parser with LazyLogging {
override def parseContents(scalaContents: Seq[(String, String)]): Seq[AST] = {
profileFunc(logger, "Parser", () => {
val temp = scala.reflect.runtime.currentMirror.mkToolBox()
val toolbox: ToolBox[JavaUniverse] = temp.asInstanceOf[ToolBox[JavaUniverse]]
scalaContents.map(c => {
val (filename, content) = c
logger.debug(s"Parsing content of file $filename")
AST(filename, parseContent(toolbox, content))
})
})
}
private def parseContent(toolbox: ToolBox[JavaUniverse], scalaContent: String): Tree = {
toolbox.parse(scalaContent).asInstanceOf[Tree]
}
}
示例11: Eval
//设置package包名称以及导入依赖的类
package openmp.executor
import lift.arithmetic._
import ir.ast.Lambda
import scala.reflect.runtime._
import scala.tools.reflect.ToolBox
object Eval {
def apply(code: String): Lambda = {
eval(code).asInstanceOf[Lambda]
}
def getMethod(code:String): Seq[ArithExpr] => Lambda = {
eval(code).asInstanceOf[Seq[ArithExpr] => Lambda]
}
def eval(code: String): Any = {
val mirror = universe.runtimeMirror(getClass.getClassLoader)
val tb = mirror.mkToolBox()
val tree = tb.parse(s"""
|import arithmetic._
|import apart.arithmetic._
|import ir._
|import ir.ast._
|import opencl.ir._
|import opencl.ir.pattern._
|import opencl.ir.ast._
|$code
""".stripMargin)
tb.eval(tree)
}
}
示例12: Eval
//设置package包名称以及导入依赖的类
package opencl.executor
import ir.ast.Lambda
import lift.arithmetic._
import scala.reflect.runtime._
import scala.tools.reflect.ToolBox
object Eval {
def apply(code: String): Lambda = {
eval(code).asInstanceOf[Lambda]
}
def getMethod(code:String): Seq[ArithExpr] => Lambda = {
eval(code).asInstanceOf[Seq[ArithExpr] => Lambda]
}
def eval(code: String): Any = {
val mirror = universe.runtimeMirror(getClass.getClassLoader)
val tb = mirror.mkToolBox()
val tree = tb.parse(s"""
|import arithmetic._
|import lift.arithmetic._
|import ir._
|import ir.ast._
|import opencl.ir._
|import opencl.ir.pattern._
|import opencl.ir.ast._
|$code
""".stripMargin)
tb.eval(tree)
}
}
示例13: Eval
//设置package包名称以及导入依赖的类
package c.executor
import lift.arithmetic._
import ir.ast.Lambda
import scala.reflect.runtime._
import scala.tools.reflect.ToolBox
object Eval {
def apply(code: String): Lambda = {
eval(code).asInstanceOf[Lambda]
}
def getMethod(code:String): Seq[ArithExpr] => Lambda = {
eval(code).asInstanceOf[Seq[ArithExpr] => Lambda]
}
def eval(code: String): Any = {
val mirror = universe.runtimeMirror(getClass.getClassLoader)
val tb = mirror.mkToolBox()
val tree = tb.parse(s"""
|import arithmetic._
|import apart.arithmetic._
|import ir._
|import ir.ast._
|import opencl.ir._
|import opencl.ir.pattern._
|import opencl.ir.ast._
|$code
""".stripMargin)
tb.eval(tree)
}
}
示例14: areEqual
//设置package包名称以及导入依赖的类
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)
}
}
示例15: log
//设置package包名称以及导入依赖的类
package macroni.compiler
import scala.reflect.internal.util.Position
import scala.reflect.runtime.currentMirror
import scala.reflect.runtime.universe.Tree
import scala.tools.reflect.{FrontEnd, ToolBox}
import scala.util.{Try, Success, Failure}
import scala.collection.mutable
import macroni.macros.CompilerSettings
//TODO: needed because FrontEnd stores `infos` in a LinkedHashSet.
// Thus, messages with the same hashcode are lost. This can happen
// in quasiquotes, where the position may be NoPosition.
trait InfoListFrontEnd extends FrontEnd {
val infoList = new mutable.ArrayBuffer[Info]
override def log(pos: Position, msg: String, severity: Severity) {
super.log(pos, msg, severity)
infoList += Info(pos, msg, severity)
}
override def reset() {
super.reset()
infoList.clear()
}
}
class SilentReporter extends InfoListFrontEnd {
def display(info: Info) {}
def interactive() {}
}
object Config {
val compilerPlugins = CompilerSettings().filter(_.startsWith("-Xplugin")).mkString(" ")
val options = compilerPlugins
}
object Compiler {
def apply(tree: Tree): CompileResult = {
val reporter = new SilentReporter
val toolbox = currentMirror.mkToolBox(reporter, Config.options)
Try(toolbox.typecheck(tree)) match {
case Success(typedTree) => CompileResult(tree, toolbox.untypecheck(typedTree), reporter)
case Failure(e) => CompileResult(tree, e, reporter)
}
}
}