Script.java 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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, new StackTrace(instr.getLine(), returnStack, code));
  93. break;
  94. }
  95. if(System.nanoTime() > endTime) {
  96. isHolded = true;
  97. scriptManager.getScheduler().scheduleTask(() -> {
  98. if(!shouldTerm()) {
  99. isHolded = false;
  100. run();
  101. }
  102. }, 1);
  103. scriptManager.getLogger().print("auto scheduler was activated", null, instr.getName(), name, this, new StackTrace(instr.getLine(), returnStack, code));
  104. break;
  105. }
  106. }
  107. //System.out.println(count + " " + (15_000_000 / count));
  108. if(shouldTerm() && !dataStack.isEmpty()) {
  109. scriptManager.getLogger().print(String.format("data stack is not empty %s", dataStack));
  110. }
  111. }
  112. public String getName() {
  113. return name;
  114. }
  115. public int getId() {
  116. return id;
  117. }
  118. public StackTrace getStackTrace() {
  119. if(lineIndex >= 0 && lineIndex < code.length) {
  120. return new StackTrace(code[lineIndex].getLine(), returnStack, code);
  121. }
  122. return null;
  123. }
  124. public ScriptManager getScriptManager() {
  125. return scriptManager;
  126. }
  127. private HashMap<String, Integer> getLabels() {
  128. return inFunction.isEmpty() ? labels : localLabels.get(inFunction.peek());
  129. }
  130. public void gotoLabel(String label, boolean error, int add) {
  131. lineIndex = getLabels().getOrDefault(label, error ? null : lineIndex) + add;
  132. }
  133. public void gotoLabel(String label, boolean error) {
  134. gotoLabel(label, error, 0);
  135. }
  136. public void goSub(String label) {
  137. int line = getLabels().get(label);
  138. returnStack.push(lineIndex);
  139. lineIndex = line;
  140. returnVarPop.push(false);
  141. }
  142. public void jumpTo(int jump) {
  143. lineIndex = jump;
  144. }
  145. public void setIfState(boolean state) {
  146. ifState.pop();
  147. ifState.push(state);
  148. }
  149. public boolean getIfState() {
  150. return ifState.peek();
  151. }
  152. public void handleFunction(String function, InputProvider[] in) throws Exception {
  153. Integer sub = functions.get(function);
  154. if(sub == null) {
  155. throw new IllegalArgumentException(String.format("function '%s' does not exist", function));
  156. }
  157. UserFunction uf = (UserFunction) code[sub];
  158. String[] args = uf.getArgumentNames();
  159. HashMap<String, Variable> lvars = new HashMap<>();
  160. if(in.length != args.length) {
  161. throw new IllegalArgumentException(String.format("invalid number of arguments at function '%s'", function));
  162. }
  163. for(int i = 0; i < in.length; i++) {
  164. Variable v = new Variable(args[i]);
  165. v.set(this, in[i].get(this));
  166. lvars.put(args[i], v);
  167. }
  168. ifState.push(true);
  169. localVars.push(lvars);
  170. returnStack.push(lineIndex);
  171. lineIndex = sub;
  172. inFunction.push(function);
  173. returnVarPop.push(true);
  174. }
  175. public void handleReturn(ReturnWrapper wrapper) {
  176. lineIndex = returnStack.pop();
  177. if(returnVarPop.pop()) {
  178. ifState.pop();
  179. inFunction.pop();
  180. localVars.pop();
  181. if(wrapper != null && !code[lineIndex].shouldNotReturnValue()) {
  182. dataStack.add(wrapper);
  183. }
  184. }
  185. }
  186. public Variable getOrAddLocalVariable(String name) {
  187. HashMap<String, Variable> map = localVars.peek();
  188. Variable v = map.get(name);
  189. if(v != null) {
  190. return v;
  191. }
  192. v = new Variable(name);
  193. map.put(name, v);
  194. return v;
  195. }
  196. public InputProvider peekDataStack() {
  197. return dataStack.peek();
  198. }
  199. public void term() {
  200. lineIndex = code.length;
  201. isWaiting = false;
  202. }
  203. public boolean shouldTerm() {
  204. return (lineIndex < 0 || lineIndex >= code.length) && !isWaiting;
  205. }
  206. public void onTerm() {
  207. onTerm.accept(this);
  208. closeables.forEach(c -> {
  209. scriptManager.getLogger().print("prepared statement not closed", null, null, name, this, null);
  210. try {
  211. c.close();
  212. } catch(Exception ex) {
  213. scriptManager.getLogger().print("cannot close closeable in script", ex, null, name, this, null);
  214. }
  215. });
  216. }
  217. public void setHolded(boolean b) {
  218. isHolded = b;
  219. }
  220. public boolean isHolded() {
  221. return isHolded;
  222. }
  223. public void setWaiting() {
  224. isWaiting = true;
  225. }
  226. public boolean isWaiting() {
  227. return isWaiting;
  228. }
  229. public void setVar(String name, Object value) {
  230. Variable v = vars.get(name);
  231. if(v != null) {
  232. v.set(this, value);
  233. }
  234. }
  235. public Variable getVar(String name) {
  236. return vars.get(name);
  237. }
  238. public boolean isEventLoaded(String event) {
  239. return loadedEvents.contains(event);
  240. }
  241. public boolean loadEvent(String event) {
  242. return loadedEvents.add(event);
  243. }
  244. public boolean unloadEvent(String event) {
  245. return loadedEvents.remove(event);
  246. }
  247. public void setStackTrace(boolean b) {
  248. stackTrace = b;
  249. }
  250. public synchronized void addCloseable(AutoCloseable closeable) {
  251. closeables.add(closeable);
  252. }
  253. public synchronized void removeCloseable(AutoCloseable closeable) {
  254. closeables.remove(closeable);
  255. }
  256. @Override
  257. public int hashCode() {
  258. return id;
  259. }
  260. @Override
  261. public boolean equals(Object o) {
  262. return o != null && o instanceof Script && ((Script) o).id == id;
  263. }
  264. }