Script.java 11 KB

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