-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Scripting solution #10491
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Scripting solution #10491
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
ec116d6
Scripting Solution: `scala` can compile & run *.scala files
anatoliykmetyuk 86db69d
Test framework for the scripting engine implemented
anatoliykmetyuk f3ab85d
`scala` binary can execute scripts
anatoliykmetyuk a62d9cb
Notify the user which main methods were discovered
anatoliykmetyuk ec8cd9f
Remove redundant flags from scripting tests
anatoliykmetyuk d59bec7
Delete temporary directory after script execution
anatoliykmetyuk 6e7209f
Avoid null in the scripting driver
anatoliykmetyuk 246b5a1
Add scripting docs
anatoliykmetyuk File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
package dotty.tools.scripting | ||
|
||
import java.io.File | ||
|
||
/** Main entry point to the Scripting execution engine */ | ||
object Main: | ||
/** All arguments before -script <target_script> are compiler arguments. | ||
All arguments afterwards are script arguments.*/ | ||
def distinguishArgs(args: Array[String]): (Array[String], File, Array[String]) = | ||
val (compilerArgs, rest) = args.splitAt(args.indexOf("-script")) | ||
val file = File(rest(1)) | ||
val scriptArgs = rest.drop(2) | ||
(compilerArgs, file, scriptArgs) | ||
end distinguishArgs | ||
|
||
def main(args: Array[String]): Unit = | ||
val (compilerArgs, scriptFile, scriptArgs) = distinguishArgs(args) | ||
try ScriptingDriver(compilerArgs, scriptFile, scriptArgs).compileAndRun() | ||
catch | ||
case ScriptingException(msg) => | ||
println(s"Error: $msg") | ||
sys.exit(1) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
package dotty.tools.scripting | ||
|
||
import java.nio.file.{ Files, Path } | ||
import java.io.File | ||
import java.net.{ URL, URLClassLoader } | ||
import java.lang.reflect.{ Modifier, Method } | ||
|
||
import scala.jdk.CollectionConverters._ | ||
|
||
import dotty.tools.dotc.{ Driver, Compiler } | ||
import dotty.tools.dotc.core.Contexts, Contexts.{ Context, ContextBase, ctx } | ||
import dotty.tools.dotc.config.CompilerCommand | ||
import dotty.tools.io.{ PlainDirectory, Directory } | ||
import dotty.tools.dotc.reporting.Reporter | ||
import dotty.tools.dotc.config.Settings.Setting._ | ||
|
||
import sys.process._ | ||
|
||
class ScriptingDriver(compilerArgs: Array[String], scriptFile: File, scriptArgs: Array[String]) extends Driver: | ||
def compileAndRun(): Unit = | ||
val outDir = Files.createTempDirectory("scala3-scripting") | ||
val (toCompile, rootCtx) = setup(compilerArgs :+ scriptFile.getAbsolutePath, initCtx.fresh) | ||
given Context = rootCtx.fresh.setSetting(rootCtx.settings.outputDir, | ||
new PlainDirectory(Directory(outDir))) | ||
|
||
if doCompile(newCompiler, toCompile).hasErrors then | ||
throw ScriptingException("Errors encountered during compilation") | ||
|
||
try detectMainMethod(outDir, ctx.settings.classpath.value).invoke(null, scriptArgs) | ||
catch | ||
case e: java.lang.reflect.InvocationTargetException => | ||
throw e.getCause | ||
finally | ||
deleteFile(outDir.toFile) | ||
end compileAndRun | ||
|
||
private def deleteFile(target: File): Unit = | ||
if target.isDirectory then | ||
for member <- target.listFiles.toList | ||
do deleteFile(member) | ||
target.delete() | ||
end deleteFile | ||
|
||
private def detectMainMethod(outDir: Path, classpath: String): Method = | ||
val outDirURL = outDir.toUri.toURL | ||
val classpathUrls = classpath.split(":").map(File(_).toURI.toURL) | ||
val cl = URLClassLoader(classpathUrls :+ outDirURL) | ||
|
||
def collectMainMethods(target: File, path: String): List[Method] = | ||
val nameWithoutExtension = target.getName.takeWhile(_ != '.') | ||
val targetPath = | ||
if path.nonEmpty then s"${path}.${nameWithoutExtension}" | ||
else nameWithoutExtension | ||
|
||
if target.isDirectory then | ||
for | ||
packageMember <- target.listFiles.toList | ||
membersMainMethod <- collectMainMethods(packageMember, targetPath) | ||
yield membersMainMethod | ||
else if target.getName.endsWith(".class") then | ||
val cls = cl.loadClass(targetPath) | ||
try | ||
val method = cls.getMethod("main", classOf[Array[String]]) | ||
if Modifier.isStatic(method.getModifiers) then List(method) else Nil | ||
catch | ||
case _: java.lang.NoSuchMethodException => Nil | ||
else Nil | ||
end collectMainMethods | ||
|
||
val candidates = for | ||
file <- outDir.toFile.listFiles.toList | ||
method <- collectMainMethods(file, "") | ||
yield method | ||
|
||
candidates match | ||
case Nil => | ||
throw ScriptingException("No main methods detected in your script") | ||
case _ :: _ :: _ => | ||
throw ScriptingException("A script must contain only one main method. " + | ||
s"Detected the following main methods:\n${candidates.mkString("\n")}") | ||
case m :: Nil => m | ||
end match | ||
end detectMainMethod | ||
end ScriptingDriver | ||
|
||
case class ScriptingException(msg: String) extends RuntimeException(msg) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
@main def Test = assert(2 + 2 == 4) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
World |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
@main def Test(name: String) = | ||
assert(name == "World") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
package dotty | ||
package tools | ||
package scripting | ||
|
||
import java.io.File | ||
|
||
import org.junit.Test | ||
|
||
import vulpix.TestConfiguration | ||
|
||
|
||
/** Runs all tests contained in `compiler/test-resources/repl/` */ | ||
class ScriptingTests: | ||
extension (str: String) def dropExtension = | ||
str.reverse.dropWhile(_ != '.').drop(1).reverse | ||
|
||
@Test def scriptingTests = | ||
val testFiles = scripts("/scripting") | ||
|
||
val argss: Map[String, Array[String]] = ( | ||
for | ||
argFile <- testFiles | ||
if argFile.getName.endsWith(".args") | ||
name = argFile.getName.dropExtension | ||
scriptArgs = readLines(argFile).toArray | ||
yield name -> scriptArgs).toMap | ||
|
||
for | ||
scriptFile <- testFiles | ||
if scriptFile.getName.endsWith(".scala") | ||
name = scriptFile.getName.dropExtension | ||
scriptArgs = argss.getOrElse(name, Array.empty[String]) | ||
do | ||
ScriptingDriver( | ||
compilerArgs = Array( | ||
"-classpath", TestConfiguration.basicClasspath), | ||
scriptFile = scriptFile, | ||
scriptArgs = scriptArgs | ||
).compileAndRun() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
package dotty.tools | ||
|
||
import java.io.File | ||
import java.nio.charset.StandardCharsets.UTF_8 | ||
|
||
import scala.io.Source | ||
import scala.util.Using.resource | ||
|
||
def scripts(path: String): Array[File] = { | ||
val dir = new File(getClass.getResource(path).getPath) | ||
assert(dir.exists && dir.isDirectory, "Couldn't load scripts dir") | ||
dir.listFiles | ||
} | ||
|
||
private def withFile[T](file: File)(action: Source => T): T = | ||
resource(Source.fromFile(file, UTF_8.name))(action) | ||
|
||
def readLines(f: File): List[String] = withFile(f)(_.getLines.toList) | ||
def readFile(f: File): String = withFile(f)(_.mkString) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1 change: 1 addition & 0 deletions
1
staging/test/scala/quoted/staging/repl/StagingScriptedReplTests.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.