- 
                Notifications
    You must be signed in to change notification settings 
- Fork 1.1k
          Implement programmatic ReplMain API that allows binding local variables
          #24257
        
          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
          
     Open
      
      
            lihaoyi
  wants to merge
  2
  commits into
  scala:main
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
lihaoyi:repl-bindings
  
      
      
   
  
    
  
  
  
 
  
      
    base: main
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
  
     Open
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            2 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      
    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
    
  
  
    
              
  
    
      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,60 @@ | ||
| package dotty.tools.repl | ||
|  | ||
| import java.io.PrintStream | ||
|  | ||
| class ReplMain( | ||
| settings: Array[String] = Array.empty, | ||
| out: PrintStream = Console.out, | ||
| classLoader: Option[ClassLoader] = Some(getClass.getClassLoader), | ||
| predefCode: String = "", | ||
| testCode: String = "" | ||
| ): | ||
| def run(bindings: ReplMain.Bind[_]*): Any = | ||
| try | ||
| ReplMain.currentBindings.set(bindings.map{bind => bind.name -> bind.value}.toMap) | ||
|  | ||
| val bindingsPredef = bindings | ||
| .map { case bind => | ||
| s"def ${bind.name}: ${bind.typeName.value} = dotty.tools.repl.ReplMain.currentBinding[${bind.typeName.value}](\"${bind.name}\")" | ||
| } | ||
| .mkString("\n") | ||
|  | ||
| val fullPredef = | ||
| ReplDriver.pprintImport + | ||
| (if bindingsPredef.nonEmpty then s"\n$bindingsPredef\n" else "") + | ||
| (if predefCode.nonEmpty then s"\n$predefCode\n" else "") | ||
|  | ||
| val driver = new ReplDriver(settings, out, classLoader, fullPredef) | ||
|  | ||
| if (testCode == "") driver.tryRunning | ||
| else driver.runUntilQuit(using driver.initialState)( | ||
| new java.io.ByteArrayInputStream(testCode.getBytes()) | ||
| ) | ||
| () | ||
| finally | ||
| ReplMain.currentBindings.set(null) | ||
|  | ||
|  | ||
| object ReplMain: | ||
| final case class TypeName[A](value: String) | ||
| object TypeName extends TypeNamePlatform | ||
|  | ||
| import scala.quoted._ | ||
|  | ||
| trait TypeNamePlatform: | ||
| inline given [A]: TypeName[A] = ${TypeNamePlatform.impl[A]} | ||
|  | ||
| object TypeNamePlatform: | ||
| def impl[A](using t: Type[A], ctx: Quotes): Expr[TypeName[A]] = | ||
| '{TypeName[A](${Expr(Type.show[A])})} | ||
|  | ||
|  | ||
| case class Bind[T](name: String, value: () => T)(implicit val typeName: TypeName[T]) | ||
| object Bind: | ||
| implicit def ammoniteReplArrowBinder[T](t: (String, T))(implicit typeName: TypeName[T]): Bind[T] = { | ||
| Bind(t._1, () => t._2)(typeName) | ||
| } | ||
|  | ||
| def currentBinding[T](s: String): T = currentBindings.get().apply(s).apply().asInstanceOf[T] | ||
|  | ||
| private val currentBindings = new ThreadLocal[Map[String, () => Any]]() | 
  
    
      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,73 @@ | ||
| package dotty.tools | ||
| package repl | ||
|  | ||
| import scala.language.unsafeNulls | ||
|  | ||
| import java.io.{ByteArrayOutputStream, PrintStream} | ||
| import java.nio.charset.StandardCharsets | ||
|  | ||
| import vulpix.TestConfiguration | ||
| import org.junit.Test | ||
| import org.junit.Assert._ | ||
|  | ||
| /** Tests for the programmatic REPL API (ReplMain) */ | ||
| class ReplMainTest: | ||
|  | ||
| private val defaultOptions = Array("-classpath", TestConfiguration.withCompilerClasspath) | ||
|  | ||
| private def captureOutput(body: PrintStream => Unit): String = | ||
| val out = new ByteArrayOutputStream() | ||
| val ps = new PrintStream(out, true, StandardCharsets.UTF_8.name) | ||
| body(ps) | ||
| dotty.shaded.fansi.Str(out.toString(StandardCharsets.UTF_8.name)).plainText | ||
|  | ||
| @Test def basicBinding(): Unit = | ||
| val output = captureOutput { out => | ||
| val replMain = new ReplMain( | ||
| settings = defaultOptions, | ||
| out = out, | ||
| testCode = "test" | ||
| ) | ||
|  | ||
| replMain.run("test" -> 42) | ||
| } | ||
|  | ||
| assertTrue(output.contains("val res0: Int = 42")) | ||
|  | ||
| @Test def multipleBindings(): Unit = | ||
| val output = captureOutput { out => | ||
| val replMain = new ReplMain( | ||
| settings = defaultOptions, | ||
| out = out, | ||
| testCode = "x\ny\nz" | ||
| ) | ||
|  | ||
| replMain.run( | ||
| "x" -> 1, | ||
| "y" -> "hello", | ||
| "z" -> true | ||
| ) | ||
| } | ||
|  | ||
| assertTrue(output.contains("val res0: Int = 1")) | ||
| assertTrue(output.contains("val res1: String = \"hello\"")) | ||
| assertTrue(output.contains("val res2: Boolean = true")) | ||
|  | ||
| @Test def bindingTypes(): Unit = | ||
| val output = captureOutput { out => | ||
| val replMain = new ReplMain( | ||
| settings = defaultOptions ++ Array("-repl-quit-after-init"), | ||
| out = out, | ||
| testCode = "list\nmap" | ||
| ) | ||
|  | ||
| replMain.run( | ||
| "list" -> List(1, 2, 3), | ||
| "map" -> Map(1 -> "hello") | ||
| ) | ||
| } | ||
|  | ||
| assertTrue(output.contains("val res0: List[Int] = List(1, 2, 3)")) | ||
| assertTrue(output.contains("val res1: Map[Int, String] = Map(1 -> \"hello\")")) | ||
|  | ||
| end ReplMainTest | 
  
    
      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
    
  
  
    
              
      
      Oops, something went wrong.
        
    
  
  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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Lower in this file there is defined
final def bind(name: String, value: Any)which is a stub. We can either try to adapt logic to take advantage of this API which might have been used by existing tooling, or we can remove it. It's used inConsoleInterface.javaThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
also good to explore significance with the java scripting api (JSR 223)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The current API is modelled after the Ammonite API, which is
Configure(...flags...).run(...bindings...). There are other ways we could design the API (builders, setters, etc.) but I think the Ammonite API is a reasonable starting point. IMO ifdef binddoesn't do anything, and anyway has the wrong signature (we need to capture the type name), we can just remove it.JSR223 support could be done, but I think that would be a very different use case than the programmatic use case supported here, and can come in a separate PR if anyone asks for it