All Downloads are FREE. Search and download functionalities are using the official Maven repository.

.10.dp.source-code.eval.scala Maven / Gradle / Ivy

The newest version!
//-- license info
/*
   Copyright 2010 Aaron J. Radke

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package cc.drx

/* Eval object to behave like Twitter's eval but more drx like available api's */
object Eval{

  import scala.reflect.runtime._
  import scala.reflect.runtime.universe._
  import scala.tools.reflect.ToolBox

  // import scala.reflect.runtime.universe //val cm = universe.runtimeMirror(getClass.getClassLoader)

  private val cm = universe.runtimeMirror(getClass.getClassLoader)
  private val toolbox = cm.mkToolBox()
  // private lazy val toolbox = scala.reflect.runtime.currentMirror.mkToolBox()

  type EvalExpr = () => Any
  // def compile(code: String): () => Any = toolbox compile treeOf(code)
  def compile(code: String):EvalExpr = {
    val tree = toolbox parse code
    toolbox compile tree
  }

  def evalAny(code: String): Any = compile(code)()

  def eval[T](code: String): T = evalAny(code).asInstanceOf[T]

  def main(args:Array[String]) = {
    val argsCode = args.mkString(" ").trim
    val code = if(argsCode != "") argsCode else "2+2"
    val res = eval[Int]( code )
    println(res)
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy