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


Scala ToolBox类代码示例

本文整理汇总了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]
  }
} 
开发者ID:defvar,项目名称:knot,代码行数:27,代码来源:Compiler.scala

示例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"))
} 
开发者ID:cuzfrog,项目名称:WebDriverServ,代码行数:25,代码来源:RuntimeCompilationTest.scala

示例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]
  }
} 
开发者ID:christian-schlichtherle,项目名称:akka-game-of-life,代码行数:34,代码来源:Main.scala

示例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]
  }
} 
开发者ID:outr,项目名称:uberterm,代码行数:19,代码来源:ScalaToolboxInterpreter.scala

示例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.")
  }

} 
开发者ID:cuzfrog,项目名称:WebDriverServ,代码行数:24,代码来源:RuntimeCompiler.scala

示例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))
  }
  
  
  
} 
开发者ID:bingrao,项目名称:Scala-AST,代码行数:39,代码来源:CompilerTree.scala

示例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)
  }
} 
开发者ID:luax,项目名称:scala-immutability-plugin,代码行数:41,代码来源:TestUtils.scala

示例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]
} 
开发者ID:cuzfrog,项目名称:macros,代码行数:22,代码来源:RuntimeCompiler.scala

示例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])
  }
} 
开发者ID:oleg-py,项目名称:mco,代码行数:22,代码来源:CompileAs.scala

示例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]
  }

} 
开发者ID:viZu,项目名称:nasca,代码行数:31,代码来源:ReflectParser.scala

示例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)
  }
} 
开发者ID:lift-project,项目名称:lift,代码行数:35,代码来源:Eval.scala

示例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)
  }
} 
开发者ID:lift-project,项目名称:lift,代码行数:35,代码来源:Eval.scala

示例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)
  }
} 
开发者ID:lift-project,项目名称:lift,代码行数:35,代码来源:Eval.scala

示例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)
  }

} 
开发者ID:aishfenton,项目名称:Argus,代码行数:46,代码来源:ASTMatchers.scala

示例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)
    }
  }
} 
开发者ID:cornerman,项目名称:macroni,代码行数:50,代码来源:Compiler.scala


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