diff options
-rw-r--r-- | libraries/eval/Eval.scala | 28 | ||||
-rw-r--r-- | libraries/eval/test/EvalTest.scala | 21 |
2 files changed, 44 insertions, 5 deletions
diff --git a/libraries/eval/Eval.scala b/libraries/eval/Eval.scala index c752eba..2b22bcb 100644 --- a/libraries/eval/Eval.scala +++ b/libraries/eval/Eval.scala @@ -96,6 +96,34 @@ class Eval { apply[T](code, false) } + /** + * Check if code is Eval-able. + * @throw CompilerException if not Eval-able. + */ + def check(code: String) { + val id = uniqueId(code) + val className = "Evaluator__" + id + val wrappedCode = wrapCodeInClass(className, code) + compile(wrappedCode) // may throw CompilerException + } + + /** + * Check if files are Eval-able. + * @throw CompilerException if not Eval-able. + */ + def check(files: File*) { + val code = files.map { scala.io.Source.fromFile(_).mkString }.mkString("\n") + check(code) + } + + /** + * Check if stream is Eval-able. + * @throw CompilerException if not Eval-able. + */ + def check(stream: InputStream) { + check(scala.io.Source.fromInputStream(stream).mkString) + } + private def uniqueId(code: String): String = { val digest = MessageDigest.getInstance("SHA-1").digest(code.getBytes()) val sha = new BigInteger(1, digest).toString(16) diff --git a/libraries/eval/test/EvalTest.scala b/libraries/eval/test/EvalTest.scala index 187d0d3..3541381 100644 --- a/libraries/eval/test/EvalTest.scala +++ b/libraries/eval/test/EvalTest.scala @@ -5,31 +5,42 @@ import java.io.{File, FileOutputStream} import com.twitter.io.TempFile -object EvaluatorSpec extends Specification { +object EvalSpec extends Specification { "Evaluator" should { "apply('expression')" in { - Eval[Int]("1 + 1") mustEqual 2 + (new Eval).apply[Int]("1 + 1") mustEqual 2 } "apply(new File(...))" in { - Eval[Int](TempFile.fromResourcePath("/OnePlusOne.scala")) mustEqual 2 + (new Eval).apply[Int](TempFile.fromResourcePath("/OnePlusOne.scala")) mustEqual 2 } "apply(new File(...), new File(...))" in { - val derived = Eval[() => String]( + val derived = (new Eval).apply[() => String]( TempFile.fromResourcePath("/Base.scala"), TempFile.fromResourcePath("/Derived.scala")) derived() mustEqual "hello" } "apply(InputStream)" in { - Eval[Int](getClass.getResourceAsStream("/OnePlusOne.scala")) mustEqual 2 + (new Eval).apply[Int](getClass.getResourceAsStream("/OnePlusOne.scala")) mustEqual 2 } "inPlace('expression')" in { + // Old object API works Eval.compile("object Doubler { def apply(n: Int) = n * 2 }") Eval.inPlace[Int]("Doubler(2)") mustEqual 4 Eval.inPlace[Int]("Doubler(14)") mustEqual 28 + // New class API fails + // val eval = new Eval + // eval.compile("object Doubler { def apply(n: Int) = n * 2 }") + // eval.inPlace[Int]("Doubler(2)") mustEqual 4 + // eval.inPlace[Int]("Doubler(14)") mustEqual 28 + } + + "check" in { + (new Eval).check("23") mustEqual () + (new Eval).check("invalid") must throwA[Eval.CompilerException] } } } |