Script.java 10 KB

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