PageRenderTime 54ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/src/main/java/am/ik/brainfuck/scripting/BrainfuckScriptEngine.java

https://github.com/making/jbf
Java | 85 lines | 71 code | 14 blank | 0 comment | 2 complexity | 9cac704535b892a3e336486c11172eb3 MD5 | raw file
  1. package am.ik.brainfuck.scripting;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.PrintStream;
  6. import java.io.Reader;
  7. import javax.script.AbstractScriptEngine;
  8. import javax.script.Bindings;
  9. import javax.script.Compilable;
  10. import javax.script.CompiledScript;
  11. import javax.script.ScriptContext;
  12. import javax.script.ScriptEngineFactory;
  13. import javax.script.ScriptException;
  14. import am.ik.brainfuck.BFInterpreter;
  15. public class BrainfuckScriptEngine extends AbstractScriptEngine implements
  16. Compilable {
  17. private static InputStream in = System.in;
  18. private static PrintStream out = System.out;
  19. public static synchronized void setIn(InputStream in) {
  20. BrainfuckScriptEngine.in = in;
  21. }
  22. public static synchronized void setOut(PrintStream out) {
  23. BrainfuckScriptEngine.out = out;
  24. }
  25. @Override
  26. public Bindings createBindings() {
  27. throw new UnsupportedOperationException();
  28. }
  29. @Override
  30. public Object eval(String script, ScriptContext context)
  31. throws ScriptException {
  32. try {
  33. BFInterpreter interpreter = new BFInterpreter(script);
  34. synchronized (BrainfuckScriptEngine.class) {
  35. interpreter.setIn(in);
  36. interpreter.setOut(out);
  37. }
  38. interpreter.eval();
  39. } catch (Exception e) {
  40. throw new ScriptException(e);
  41. }
  42. return null;
  43. }
  44. @Override
  45. public Object eval(Reader reader, ScriptContext context)
  46. throws ScriptException {
  47. BufferedReader buffer = new BufferedReader(reader);
  48. StringBuilder builder = new StringBuilder();
  49. try {
  50. String line = null;
  51. while ((line = buffer.readLine()) != null) {
  52. builder.append(line);
  53. }
  54. } catch (IOException e) {
  55. throw new ScriptException(e);
  56. }
  57. return eval(buffer.toString(), context);
  58. }
  59. @Override
  60. public ScriptEngineFactory getFactory() {
  61. return new BrainfuckScriptEngineFactory();
  62. }
  63. @Override
  64. public CompiledScript compile(String script) throws ScriptException {
  65. throw new UnsupportedOperationException();
  66. }
  67. @Override
  68. public CompiledScript compile(Reader script) throws ScriptException {
  69. throw new UnsupportedOperationException();
  70. }
  71. }