Script.java 11 KB

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