-
-
Save mgttt/06086228f6f50e1d71b14568f7b7af4f to your computer and use it in GitHub Desktop.
tiny nashorn (javascript) interpreter
This file contains 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
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