Skip to content

Instantly share code, notes, and snippets.

@mgttt
Forked from benwaffle/JS.java
Created November 7, 2016 00:02
Show Gist options
  • Save mgttt/06086228f6f50e1d71b14568f7b7af4f to your computer and use it in GitHub Desktop.
Save mgttt/06086228f6f50e1d71b14568f7b7af4f to your computer and use it in GitHub Desktop.
tiny nashorn (javascript) interpreter
import java.util.NoSuchElementException;
import java.util.Scanner;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class JS {
public static void main(String[] args) {
ScriptEngine se = new ScriptEngineManager().getEngineByName("nashorn");
Scanner s = new Scanner(System.in);
String in = "";
System.out.print("> ");
while (true){
try {
in += s.nextLine(); // get more code
se.eval(in); // try eval
} catch (ScriptException e) {
if (e.getMessage().contains("but found eof")){ // incomplete expression
System.out.print("|\t");
} else { // JS error
in = "";
System.out.print("Error: " + e.getMessage() + "\n> ");
}
continue;
} catch (NoSuchElementException e){ // EOF, no more code
break;
}
// JS expression successfully evaluated
in = "";
System.out.print("> ");
}
s.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment