|
| 1 | +/* |
| 2 | + * scala-exercises - evaluator-compiler |
| 3 | + * Copyright (C) 2015-2016 47 Degrees, LLC. <http://www.47deg.com> |
| 4 | + */ |
| 5 | + |
| 6 | +package org.scalaexercises.evaluator |
| 7 | + |
| 8 | +import java.io.{File, PrintWriter} |
| 9 | +import java.math.BigInteger |
| 10 | +import java.security.MessageDigest |
| 11 | + |
| 12 | +import org.scalaexercises.evaluator.Eval.CompilerException |
| 13 | +import org.xeustechnologies.jcl.{JarClassLoader, JclObjectFactory} |
| 14 | + |
| 15 | +import java.net.URLClassLoader |
| 16 | +import scala.reflect.internal.util.{AbstractFileClassLoader, Position} |
| 17 | +import scala.tools.nsc.Settings |
| 18 | +import scala.tools.nsc.io.{AbstractFile, VirtualDirectory} |
| 19 | +import scala.tools.nsc.reporters._ |
| 20 | + |
| 21 | +/** |
| 22 | + * The code in this file was taken and only slightly modified from |
| 23 | + * |
| 24 | + * https://github.com/twitter/util/blob/302235a473d20735e5327d785e19b0f489b4a59f/util-eval/src/main/scala/com/twitter/util/Eval.scala |
| 25 | + * |
| 26 | + * Twitter, Inc. |
| 27 | + * |
| 28 | + * Evaluates files, strings, or input streams as Scala code, and returns the result. |
| 29 | + * |
| 30 | + * If `target` is `None`, the results are compiled to memory (and are therefore ephemeral). If |
| 31 | + * `target` is `Some(path)`, the path must point to a directory, and classes will be saved into |
| 32 | + * that directory. You can optionally pass a list of JARs to include to the classpath during |
| 33 | + * compilation and evaluation. |
| 34 | + * |
| 35 | + * The flow of evaluation is: |
| 36 | + * - wrap code in an `apply` method in a generated class |
| 37 | + * - compile the class adding the jars to the classpath |
| 38 | + * - construct an instance of that class |
| 39 | + * - return the result of `apply()` |
| 40 | + */ |
| 41 | +case class Eval(target: Option[File] = None, jars: List[File] = Nil) { |
| 42 | + @volatile var errors: Map[String, List[CompilationInfo]] = Map.empty |
| 43 | + |
| 44 | + val compilerOutputDir: AbstractFile = target match { |
| 45 | + case Some(dir) => AbstractFile.getDirectory(dir) |
| 46 | + case None => new VirtualDirectory("(memory)", None) |
| 47 | + } |
| 48 | + |
| 49 | + protected lazy val compilerSettings: Settings = new EvalSettings(compilerOutputDir) |
| 50 | + |
| 51 | + protected lazy val compilerMessageHandler: Option[Reporter] = Some(new AbstractReporter { |
| 52 | + override val settings: Settings = compilerSettings |
| 53 | + override def displayPrompt(): Unit = () |
| 54 | + override def display(pos: Position, msg: String, severity: this.type#Severity): Unit = |
| 55 | + errors += convert((pos, msg, severity.toString)) |
| 56 | + override def reset(): Unit = { |
| 57 | + super.reset() |
| 58 | + errors = Map.empty |
| 59 | + } |
| 60 | + private[this] def convert( |
| 61 | + errors: (Position, String, String)): (String, List[CompilationInfo]) = { |
| 62 | + val (pos, msg, severity) = errors |
| 63 | + (severity, CompilationInfo(msg, Some(RangePosition(pos.start, pos.point, pos.end))) :: Nil) |
| 64 | + } |
| 65 | + }) |
| 66 | + |
| 67 | + // Primary encapsulation around native Scala compiler |
| 68 | + private[this] lazy val compiler = new StringCompiler( |
| 69 | + codeWrapperLineOffset, |
| 70 | + target, |
| 71 | + compilerOutputDir, |
| 72 | + compilerSettings, |
| 73 | + compilerMessageHandler |
| 74 | + ) |
| 75 | + |
| 76 | + /** |
| 77 | + * Check if code is Eval-able. |
| 78 | + * @throws CompilerException if not Eval-able. |
| 79 | + */ |
| 80 | + def check(code: String) { |
| 81 | + val id = uniqueId(code) |
| 82 | + val className = "Evaluator__" + id |
| 83 | + val wrappedCode = wrapCodeInClass(className, code) |
| 84 | + |
| 85 | + val scalaSource = createScalaSource(className, wrappedCode) |
| 86 | + |
| 87 | + compiler.compile(scalaSource) |
| 88 | + } |
| 89 | + |
| 90 | + /** |
| 91 | + * Will generate a className of the form `Evaluator__<unique>`, |
| 92 | + * where unique is computed from the jvmID (a random number) |
| 93 | + * and a digest of code |
| 94 | + */ |
| 95 | + def execute[T](code: String, resetState: Boolean, jars: Seq[File]): T = { |
| 96 | + val id = uniqueId(code) |
| 97 | + val className = "Evaluator__" + id |
| 98 | + execute(className, code, resetState, jars) |
| 99 | + } |
| 100 | + |
| 101 | + def execute[T](className: String, code: String, resetState: Boolean, jars: Seq[File]): T = { |
| 102 | + |
| 103 | + import collection.JavaConverters._ |
| 104 | + val urlClassLoader = |
| 105 | + new URLClassLoader((jars map (_.toURI.toURL)).toArray, NullLoader) |
| 106 | + val classLoader = |
| 107 | + new AbstractFileClassLoader(compilerOutputDir, urlClassLoader) |
| 108 | + val jcl = new JarClassLoader(classLoader) |
| 109 | + |
| 110 | + val jarUrls = (jars map (_.getAbsolutePath)).toList |
| 111 | + jcl.addAll(jarUrls.asJava) |
| 112 | + jcl.add(compilerOutputDir.file.toURI.toURL) |
| 113 | + |
| 114 | + val wrappedCode = wrapCodeInClass(className, code) |
| 115 | + |
| 116 | + compiler.compile( |
| 117 | + createScalaSource(className, wrappedCode), |
| 118 | + className, |
| 119 | + resetState |
| 120 | + ) |
| 121 | + |
| 122 | + val factory = JclObjectFactory.getInstance() |
| 123 | + val instantiated = factory.create(jcl, className) |
| 124 | + val method = instantiated.getClass.getMethod("run") |
| 125 | + val result: Any = Option(method.invoke(instantiated)).getOrElse((): Unit) |
| 126 | + |
| 127 | + result.asInstanceOf[T] |
| 128 | + } |
| 129 | + |
| 130 | + private[this] def createScalaSource(fileName: String, code: String) = { |
| 131 | + val path = s"temp/src/main/scala/" |
| 132 | + val scalaSourceDir = new File(path) |
| 133 | + val scalaSource = new File(s"$path/$fileName.scala") |
| 134 | + |
| 135 | + scalaSourceDir.mkdirs() |
| 136 | + |
| 137 | + val writer = new PrintWriter(scalaSource) |
| 138 | + |
| 139 | + writer.write(code) |
| 140 | + writer.close() |
| 141 | + scalaSource |
| 142 | + } |
| 143 | + |
| 144 | + private[this] def uniqueId(code: String, idOpt: Option[Int] = Some(Eval.jvmId)): String = { |
| 145 | + val digest = MessageDigest.getInstance("SHA-1").digest(code.getBytes()) |
| 146 | + val sha = new BigInteger(1, digest).toString(16) |
| 147 | + idOpt match { |
| 148 | + case Some(i) => sha + "_" + i |
| 149 | + case _ => sha |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + /* |
| 154 | + * Wraps source code in a new class with an apply method. |
| 155 | + * NB: If this method is changed, make sure `codeWrapperLineOffset` is correct. |
| 156 | + */ |
| 157 | + private[this] def wrapCodeInClass(className: String, code: String) = { |
| 158 | + s""" |
| 159 | +class $className extends java.io.Serializable { |
| 160 | + def run() = { |
| 161 | + $code |
| 162 | + } |
| 163 | +} |
| 164 | +""" |
| 165 | + } |
| 166 | + |
| 167 | + /* |
| 168 | + * Defines the number of code lines that proceed evaluated code. |
| 169 | + * Used to ensure compile error messages report line numbers aligned with user's code. |
| 170 | + * NB: If `wrapCodeInClass(String,String)` is changed, make sure this remains correct. |
| 171 | + */ |
| 172 | + private[this] val codeWrapperLineOffset = 2 |
| 173 | + |
| 174 | + class EvalSettings(output: AbstractFile) extends Settings { |
| 175 | + nowarnings.value = true // warnings are exceptions, so disable |
| 176 | + outputDirs.setSingleOutput(output) |
| 177 | + if (jars.nonEmpty) { |
| 178 | + val newJars = (jars :+ output.file).mkString(File.pathSeparator) |
| 179 | + classpath.value = newJars |
| 180 | + bootclasspath.value = newJars |
| 181 | + } |
| 182 | + } |
| 183 | +} |
| 184 | + |
| 185 | +object Eval { |
| 186 | + private val jvmId = java.lang.Math.abs(new java.util.Random().nextInt()) |
| 187 | + |
| 188 | + class CompilerException(val messages: List[List[String]]) |
| 189 | + extends Exception("Compiler exception " + messages.map(_.mkString("\n")).mkString("\n")) |
| 190 | +} |
0 commit comments