Script.java 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. package me.hammerle.snuviscript.code;
  2. import me.hammerle.snuviscript.inputprovider.InputProvider;
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.InputStream;
  6. import java.util.ArrayList;
  7. import java.util.HashMap;
  8. import java.util.HashSet;
  9. import java.util.Stack;
  10. import java.util.function.Consumer;
  11. import me.hammerle.snuviscript.exceptions.PreScriptException;
  12. import me.hammerle.snuviscript.exceptions.StackTrace;
  13. import me.hammerle.snuviscript.inputprovider.ReturnWrapper;
  14. import me.hammerle.snuviscript.tokenizer.Tokenizer;
  15. import me.hammerle.snuviscript.inputprovider.Variable;
  16. import me.hammerle.snuviscript.instructions.Instruction;
  17. import me.hammerle.snuviscript.instructions.UserFunction;
  18. public final class Script {
  19. private static int idCounter = 0;
  20. private final int id;
  21. private final String name;
  22. private final ScriptManager scriptManager;
  23. private int lineIndex = 0;
  24. private final Instruction[] code;
  25. private final Stack<InputProvider> dataStack = new Stack<>();
  26. private final Stack<Integer> returnStack = new Stack<>();
  27. private final HashMap<String, Integer> labels = new HashMap<>();
  28. private final HashMap<String, HashMap<String, Integer>> localLabels = new HashMap<>();
  29. private final HashMap<String, Variable> vars = new HashMap<>();
  30. private final Stack<HashMap<String, Variable>> localVars = new Stack<>();
  31. private final HashMap<String, Integer> functions = new HashMap<>();
  32. private Stack<Boolean> ifState = new Stack<>();
  33. private Stack<String> inFunction = new Stack<>();
  34. private Stack<Boolean> returnVarPop = new Stack<>();
  35. // waiting scripts stop executing and run again on an event
  36. private boolean isWaiting;
  37. // holded scripts do not receive events
  38. private boolean isHolded;
  39. private boolean stackTrace;
  40. private HashSet<String> loadedEvents = new HashSet<>();
  41. private final Consumer<Script> onTerm;
  42. private final ArrayList<AutoCloseable> closeables = new ArrayList<>();
  43. public Script(ScriptManager sm, Consumer<Script> onTerm, String name, String... path) {
  44. ifState.push(true);
  45. this.id = idCounter++;
  46. this.name = name;
  47. this.scriptManager = sm;
  48. this.onTerm = onTerm;
  49. Tokenizer t = new Tokenizer();
  50. InputStream[] streams = new InputStream[path.length];
  51. for(int i = 0; i < streams.length; i++) {
  52. try {
  53. streams[i] = new FileInputStream(path[i]);
  54. } catch(FileNotFoundException ex) {
  55. throw new PreScriptException(ex.getMessage(), -1);
  56. }
  57. }
  58. Compiler c = new Compiler();
  59. this.code = c.compile(t.tokenize(streams), labels, vars, functions, localLabels);
  60. // for(Instruction in : code) {
  61. // System.out.println(in);
  62. // }
  63. }
  64. private void pushIfNotNull(InputProvider in) {
  65. if(in != null) {
  66. dataStack.push(in);
  67. }
  68. }
  69. public void run() {
  70. isWaiting = false;
  71. // System.out.println("_________________________");
  72. long endTime = System.nanoTime() + 15_000_000;
  73. while(lineIndex < code.length && !isWaiting && !isHolded) {
  74. Instruction instr = code[lineIndex];
  75. try {
  76. // System.out.println("EXECUTE: " + instr + " " + dataStack);
  77. if(instr.getArguments() > 0) {
  78. InputProvider[] args = InputProviderArrayPool.get(instr.getArguments());
  79. for(int i = args.length - 1; i >= 0; i--) {
  80. args[i] = dataStack.pop();
  81. }
  82. pushIfNotNull(instr.execute(this, args));
  83. } else {
  84. pushIfNotNull(instr.execute(this, new InputProvider[0]));
  85. }
  86. // System.out.println("AFTER EXECUTE: " + dataStack);
  87. lineIndex++;
  88. } catch(Exception ex) {
  89. if(stackTrace) {
  90. ex.printStackTrace();
  91. }
  92. scriptManager.getLogger().print(null, ex, instr.getName(), name, this,
  93. new StackTrace(instr.getLine(), returnStack, code));
  94. break;
  95. }
  96. if(System.nanoTime() > endTime) {
  97. isHolded = true;
  98. scriptManager.getScheduler().scheduleTask(() -> {
  99. if(!shouldTerm()) {
  100. isHolded = false;
  101. run();
  102. }
  103. }, 1);
  104. scriptManager.getLogger().print("auto scheduler was activated", null,
  105. instr.getName(), name, this,
  106. new StackTrace(instr.getLine(), returnStack, code));
  107. break;
  108. }
  109. }
  110. // System.out.println(count + " " + (15_000_000 / count));
  111. if(shouldTerm() && !dataStack.isEmpty()) {
  112. scriptManager.getLogger().print(String.format("data stack is not empty %s", dataStack));
  113. }
  114. }
  115. public String getName() {
  116. return name;
  117. }
  118. public int getId() {
  119. return id;
  120. }
  121. public StackTrace getStackTrace() {
  122. if(lineIndex >= 0 && lineIndex < code.length) {
  123. return new StackTrace(code[lineIndex].getLine(), returnStack, code);
  124. }
  125. return null;
  126. }
  127. public ScriptManager getScriptManager() {
  128. return scriptManager;
  129. }
  130. private HashMap<String, Integer> getLabels() {
  131. return inFunction.isEmpty() ? labels : localLabels.get(inFunction.peek());
  132. }
  133. public void gotoLabel(String label, boolean error, int add) {
  134. lineIndex = getLabels().getOrDefault(label, error ? null : lineIndex) + add;
  135. }
  136. public void gotoLabel(String label, boolean error) {
  137. gotoLabel(label, error, 0);
  138. }
  139. public void goSub(String label) {
  140. int line = getLabels().get(label);
  141. returnStack.push(lineIndex);
  142. lineIndex = line;
  143. returnVarPop.push(false);
  144. }
  145. public void jumpTo(int jump) {
  146. lineIndex = jump;
  147. }
  148. public void setIfState(boolean state) {
  149. ifState.pop();
  150. ifState.push(state);
  151. }
  152. public boolean getIfState() {
  153. return ifState.peek();
  154. }
  155. public void handleFunction(String function, InputProvider[] in) throws Exception {
  156. Integer sub = functions.get(function);
  157. if(sub == null) {
  158. throw new IllegalArgumentException(
  159. String.format("function '%s' does not exist", function));
  160. }
  161. UserFunction uf = (UserFunction) code[sub];
  162. String[] args = uf.getArgumentNames();
  163. HashMap<String, Variable> lvars = new HashMap<>();
  164. if(in.length != args.length) {
  165. throw new IllegalArgumentException(
  166. String.format("invalid number of arguments at function '%s'", function));
  167. }
  168. for(int i = 0; i < in.length; i++) {
  169. Variable v = new Variable(args[i]);
  170. v.set(this, in[i].get(this));
  171. lvars.put(args[i], v);
  172. }
  173. ifState.push(true);
  174. localVars.push(lvars);
  175. returnStack.push(lineIndex);
  176. lineIndex = sub;
  177. inFunction.push(function);
  178. returnVarPop.push(true);
  179. }
  180. public void handleReturn(ReturnWrapper wrapper) {
  181. lineIndex = returnStack.pop();
  182. if(returnVarPop.pop()) {
  183. ifState.pop();
  184. inFunction.pop();
  185. localVars.pop();
  186. if(wrapper != null && !code[lineIndex].shouldNotReturnValue()) {
  187. dataStack.add(wrapper);
  188. }
  189. }
  190. }
  191. public Variable getOrAddLocalVariable(String name) {
  192. HashMap<String, Variable> map = localVars.peek();
  193. Variable v = map.get(name);
  194. if(v != null) {
  195. return v;
  196. }
  197. v = new Variable(name);
  198. map.put(name, v);
  199. return v;
  200. }
  201. public InputProvider peekDataStack() {
  202. return dataStack.peek();
  203. }
  204. public void term() {
  205. lineIndex = code.length;
  206. isWaiting = false;
  207. }
  208. public boolean shouldTerm() {
  209. return (lineIndex < 0 || lineIndex >= code.length) && !isWaiting;
  210. }
  211. public void onTerm() {
  212. if(onTerm != null) {
  213. onTerm.accept(this);
  214. }
  215. closeables.forEach(c -> {
  216. scriptManager.getLogger().print("prepared statement not closed", null, null, name, this,
  217. null);
  218. try {
  219. c.close();
  220. } catch(Exception ex) {
  221. scriptManager.getLogger().print("cannot close closeable in script", ex, null, name,
  222. this, null);
  223. }
  224. });
  225. }
  226. public void setHolded(boolean b) {
  227. isHolded = b;
  228. }
  229. public boolean isHolded() {
  230. return isHolded;
  231. }
  232. public void setWaiting() {
  233. isWaiting = true;
  234. }
  235. public boolean isWaiting() {
  236. return isWaiting;
  237. }
  238. public void setVar(String name, Object value) {
  239. Variable v = vars.get(name);
  240. if(v != null) {
  241. v.set(this, value);
  242. }
  243. }
  244. public Variable getVar(String name) {
  245. return vars.get(name);
  246. }
  247. public boolean isEventLoaded(String event) {
  248. return loadedEvents.contains(event);
  249. }
  250. public boolean loadEvent(String event) {
  251. return loadedEvents.add(event);
  252. }
  253. public boolean unloadEvent(String event) {
  254. return loadedEvents.remove(event);
  255. }
  256. public void setStackTrace(boolean b) {
  257. stackTrace = b;
  258. }
  259. public synchronized void addCloseable(AutoCloseable closeable) {
  260. closeables.add(closeable);
  261. }
  262. public synchronized void removeCloseable(AutoCloseable closeable) {
  263. closeables.remove(closeable);
  264. }
  265. @Override
  266. public int hashCode() {
  267. return id;
  268. }
  269. @Override
  270. public boolean equals(Object o) {
  271. return o != null && o instanceof Script && ((Script) o).id == id;
  272. }
  273. }