Script.java 10 KB

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