Script.java 10 KB

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