CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-scala-lang--scala3-compiler-3

The Scala 3 compiler (Dotty) providing advanced type inference, metaprogramming capabilities, and enhanced performance for modern Scala development

Overview
Eval results
Files

repl-scripting.mddocs/

REPL and Scripting

REPL (Read-Eval-Print Loop) functionality for interactive Scala development, script execution capabilities, and JSR-223 scripting engine integration.

Capabilities

REPL Driver

Core REPL engine providing interactive compilation and execution capabilities for Scala code.

/**
 * REPL compilation and execution engine
 * Provides interactive Scala code evaluation with state preservation
 */
class ReplDriver {
  /**
   * Initialize REPL with default settings
   * Sets up compilation context and execution environment
   */
  def initialize(): Unit
  
  /**
   * Initialize REPL with custom settings
   * @param settings Compiler settings for REPL compilation
   * @param classpath Additional classpath entries for REPL
   */
  def initialize(settings: Settings, classpath: List[String]): Unit
  
  /**
   * Evaluate a line of Scala code
   * Compiles and executes the code, maintaining state between evaluations
   * @param line Scala code to evaluate
   * @return ReplResult containing evaluation outcome and value
   */
  def eval(line: String): ReplResult
  
  /**
   * Reset REPL state
   * Clears all previously defined symbols and imported names
   */
  def reset(): Unit
  
  /**
   * Get current REPL context
   * @return Compilation context with current REPL state
   */
  def currentContext: Context
  
  /**
   * Add import to REPL scope
   * @param importPath Import path to add (e.g., "scala.collection.mutable._")
   */
  def addImport(importPath: String): Unit
  
  /**
   * Get REPL history
   * @return List of previously evaluated expressions
   */
  def history: List[String]
  
  /**
   * Get defined symbols in REPL
   * @return Map of symbol names to their types
   */
  def definedSymbols: Map[String, String]
  
  /**
   * Execute multi-line code block
   * @param code Multi-line Scala code to execute
   * @return ReplResult containing execution outcome
   */
  def executeBlock(code: String): ReplResult
}

Usage Examples:

import dotty.tools.repl.ReplDriver

val repl = new ReplDriver
repl.initialize()

// Basic evaluation
val result1 = repl.eval("val x = 42")
println(result1.value) // prints: 42

val result2 = repl.eval("x * 2")
println(result2.value) // prints: 84

// Add imports
repl.addImport("scala.collection.mutable._")
val result3 = repl.eval("val buffer = ListBuffer(1, 2, 3)")

// Multi-line code
val multiLine = """
  |def factorial(n: Int): Int = 
  |  if n <= 1 then 1 
  |  else n * factorial(n - 1)
  |
  |factorial(5)
""".stripMargin

val result4 = repl.executeBlock(multiLine)
println(result4.value) // prints: 120

REPL Main Entry Point

Command-line entry point for starting the interactive REPL session.

/**
 * REPL main entry point
 * Provides command-line interface for starting interactive sessions
 */
object repl.Main {
  /**
   * Start interactive REPL session
   * @param args Command-line arguments for REPL configuration
   */
  def main(args: Array[String]): Unit
  
  /**
   * Start REPL with custom configuration
   * @param settings REPL-specific settings
   * @param initialCommands Commands to execute at startup
   */
  def startRepl(settings: ReplSettings, initialCommands: List[String]): Unit
  
  /**
   * Run REPL in batch mode (non-interactive)
   * @param commands List of commands to execute
   * @return List of results from command execution
   */
  def runBatch(commands: List[String]): List[ReplResult]
}

Usage Examples:

# Start interactive REPL
scala3-repl

# Start REPL with custom classpath
scala3-repl -classpath "lib/*:target/classes"

# Start REPL with initial imports
scala3-repl -i "import mypackage._"
// Programmatic REPL usage
import dotty.tools.repl.Main

val settings = ReplSettings(
  classpath = List("lib/mymath.jar"),
  verbose = true
)

val initialCommands = List(
  "import mymath._",
  "val pi = 3.14159"
)

Main.startRepl(settings, initialCommands)

Script Engine (JSR-223)

JSR-223 ScriptEngine implementation for integrating Scala compilation and execution into Java applications.

/**
 * JSR-223 ScriptEngine implementation
 * Provides standardized scripting interface for Java integration
 */
class ScriptEngine extends javax.script.ScriptEngine {
  /**
   * Evaluate Scala script from string
   * @param script Scala code to evaluate
   * @return Result of script evaluation
   */
  def eval(script: String): Object
  
  /**
   * Evaluate Scala script from string with bindings
   * @param script Scala code to evaluate  
   * @param bindings Variable bindings to make available in script
   * @return Result of script evaluation
   */
  def eval(script: String, bindings: javax.script.Bindings): Object
  
  /**
   * Evaluate Scala script from Reader
   * @param reader Reader containing Scala code
   * @return Result of script evaluation
   */
  def eval(reader: java.io.Reader): Object
  
  /**
   * Create new bindings for script variables
   * @return Fresh Bindings instance
   */
  def createBindings(): javax.script.Bindings
  
  /**
   * Get script engine factory
   * @return ScriptEngineFactory for this engine
   */
  def getFactory(): javax.script.ScriptEngineFactory
  
  /**
   * Get current script context
   * @return ScriptContext containing engine state
   */
  def getContext(): javax.script.ScriptContext
  
  /**
   * Set script context
   * @param context New script context to use
   */
  def setContext(context: javax.script.ScriptContext): Unit
}

Usage Examples:

// Java usage of Scala ScriptEngine
import javax.script.*;

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine scalaEngine = manager.getEngineByName("scala");

// Basic script evaluation
Object result = scalaEngine.eval("42 + 8");
System.out.println(result); // prints: 50

// Script with bindings
Bindings bindings = scalaEngine.createBindings();
bindings.put("x", 10);
bindings.put("y", 20);
Object sum = scalaEngine.eval("x + y", bindings);
System.out.println(sum); // prints: 30

// Multi-line script
String script = """
    def fibonacci(n: Int): Int = 
      if n <= 1 then n
      else fibonacci(n-1) + fibonacci(n-2)
    
    fibonacci(10)
    """;
Object fib = scalaEngine.eval(script);
System.out.println(fib); // prints: 55

REPL Commands

Built-in REPL commands for interactive development and debugging.

/**
 * REPL command system
 * Provides meta-commands for REPL interaction and introspection
 */
object ReplCommand {
  /**
   * Show help for available commands
   */
  def help(): String
  
  /**
   * Show type of expression
   * @param expr Expression to get type for
   * @return String representation of the type
   */
  def showType(expr: String): String
  
  /**
   * Show definition of symbol
   * @param name Symbol name to show definition for
   * @return String containing symbol definition
   */
  def showDefinition(name: String): String
  
  /**
   * List currently defined symbols
   * @return List of symbol names and their types
   */
  def listSymbols(): List[(String, String)]
  
  /**
   * Show REPL history
   * @return List of previously entered commands
   */
  def showHistory(): List[String]
  
  /**
   * Load Scala file into REPL
   * @param filename Path to Scala file to load
   * @return Result of loading the file
   */
  def loadFile(filename: String): ReplResult
  
  /**
   * Save REPL session to file
   * @param filename Path to save session to
   */
  def saveSession(filename: String): Unit
  
  /**
   * Execute shell command
   * @param command Shell command to execute
   * @return Output from shell command
   */
  def shell(command: String): String
}

Interactive Usage:

scala> :help
Available commands:
  :type <expr>    show the type of an expression
  :def <name>     show definition of a name
  :list          list defined names and their types
  :history       show command history
  :load <file>   load and execute a Scala file
  :save <file>   save session to file
  :! <command>   execute shell command

scala> val numbers = List(1, 2, 3, 4, 5)
val numbers: List[Int] = List(1, 2, 3, 4, 5)

scala> :type numbers.map(_ * 2)
List[Int]

scala> :def numbers
val numbers: List[Int]

scala> :list
val numbers: List[Int]

scala> :load "myScript.scala"
Loading myScript.scala...

Scripting Utilities

Utilities for script execution and file processing in REPL and scripting contexts.

/**
 * Scripting utilities for file processing and execution
 */
object ScriptingUtils {
  /**
   * Compile and execute Scala script file
   * @param scriptPath Path to Scala script file
   * @param args Arguments to pass to script
   * @return Exit code from script execution
   */
  def executeScript(scriptPath: String, args: Array[String]): Int
  
  /**
   * Compile script to bytecode
   * @param scriptContent Scala script content
   * @param outputDir Directory to write compiled classes
   * @return List of generated class files
   */
  def compileScript(scriptContent: String, outputDir: String): List[String]
  
  /**
   * Check if file is a valid Scala script
   * @param filePath Path to file to check
   * @return True if file appears to be a Scala script
   */
  def isScalaScript(filePath: String): Boolean
  
  /**
   * Extract script dependencies from comments
   * @param scriptContent Script content to analyze
   * @return List of dependency specifications
   */
  def extractDependencies(scriptContent: String): List[String]
  
  /**
   * Resolve script dependencies
   * @param dependencies List of dependency specifications
   * @return List of resolved JAR file paths
   */
  def resolveDependencies(dependencies: List[String]): List[String]
}

Types

ReplResult

/**
 * Result of REPL evaluation
 */
case class ReplResult(
  success: Boolean,           // Whether evaluation succeeded
  value: Any,                 // Result value (if successful)
  valueType: String,          // String representation of result type
  output: String,             // Standard output from evaluation
  error: Option[String]       // Error message (if failed)
)

ReplSettings

/**
 * REPL-specific configuration settings
 */
case class ReplSettings(
  classpath: List[String] = Nil,        // Additional classpath entries
  imports: List[String] = Nil,          // Auto-imports for REPL session
  verbose: Boolean = false,             // Enable verbose output
  colors: Boolean = true,               // Enable syntax coloring
  prompt: String = "scala> ",           // Command prompt string
  continuationPrompt: String = "     | ", // Multi-line continuation prompt
  maxOutputLines: Int = 1000,           // Maximum lines of output to show
  historyFile: Option[String] = None    // Path to history file
)

ScriptEngineFactory

/**
 * Factory for creating Scala script engines
 */
class ScriptEngineFactory extends javax.script.ScriptEngineFactory {
  def getEngineName(): String = "Scala Script Engine"
  def getEngineVersion(): String = "3.7.0"
  def getLanguageName(): String = "Scala"
  def getLanguageVersion(): String = "3.7.0"
  def getNames(): java.util.List[String] = java.util.List.of("scala", "scala3")
  def getMimeTypes(): java.util.List[String] = java.util.List.of("application/scala")
  def getExtensions(): java.util.List[String] = java.util.List.of("scala", "sc")
}

Install with Tessl CLI

npx tessl i tessl/maven-org-scala-lang--scala3-compiler-3

docs

context-management.md

core-compilation.md

index.md

interactive-compilation.md

java-interfaces.md

plugin-development.md

repl-scripting.md

tile.json