Script.java 11 KB

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