Script.java 11 KB

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