Skip to content

Instantly share code, notes, and snippets.

@chrisvest
Created May 29, 2015 15:34
Show Gist options
  • Save chrisvest/545a96191504a2046028 to your computer and use it in GitHub Desktop.
Save chrisvest/545a96191504a2046028 to your computer and use it in GitHub Desktop.
package repl;
import jdk.nashorn.internal.runtime.ParserException;
import jnr.ffi.LibraryLoader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.Spliterators;
import java.util.stream.Collectors;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Main
{
public static void main( String[] args ) throws Exception
{
ScriptEngineManager engineManager = new ScriptEngineManager();
ScriptEngine js = engineManager.getEngineByExtension( "js" );
BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
PrintWriter out = new PrintWriter( System.out, true );
PrintWriter err = new PrintWriter( System.err, true );
ScriptContext context = js.getContext();
context.setReader( in );
context.setWriter( out );
context.setErrorWriter( err );
loadScript( js, "nashorn:mozilla_compat.js" );
defineClass( js, System.class );
defineClass( js, LibraryLoader.class );
defineClass( js, Files.class );
defineClass( js, Paths.class );
defineClass( js, Arrays.class );
defineClass( js, Collections.class );
defineClass( js, Spliterators.class );
defineClass( js, Collectors.class );
String pstart = "js> ";
String pcont = " > ";
String source = prompt( out, in, pstart );
while ( source != null )
{
try
{
Object ret = js.eval( source, context );
if ( ret != null )
{
out.write( String.valueOf( ret ) );
out.write( '\n' );
}
}
catch ( ScriptException e )
{
if ( e.getCause() instanceof ParserException && !source.endsWith( ";;" ) )
{
source += "\n" + prompt( out, in, pcont );
continue;
}
e.printStackTrace( err );
}
catch ( Throwable e )
{
e.printStackTrace( err );
}
err.flush();
out.flush();
source = prompt( out, in, pstart );
}
}
private static void loadScript( ScriptEngine js, String script ) throws ScriptException
{
evalPrelude( js, "load(\"" + script + "\");" );
}
private static void defineClass( ScriptEngine js, Class<?> cls ) throws ScriptException
{
evalPrelude( js, "var " + cls.getSimpleName() + " = Java.type(\"" + cls.getName() + "\");" );
}
private static void evalPrelude( ScriptEngine js, String script ) throws ScriptException
{
System.err.println( script );
js.eval( script );
}
private static String prompt( PrintWriter out, BufferedReader in, String pstr ) throws IOException
{
out.write( pstr );
out.flush();
return in.readLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment