Script.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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.inputprovider.ReturnWrapper;
  13. import me.hammerle.snuviscript.tokenizer.Tokenizer;
  14. import me.hammerle.snuviscript.inputprovider.Variable;
  15. import me.hammerle.snuviscript.instructions.Instruction;
  16. import me.hammerle.snuviscript.instructions.UserFunction;
  17. public final class Script
  18. {
  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. {
  50. ifState.push(true);
  51. this.id = idCounter++;
  52. this.name = name;
  53. this.sm = sm;
  54. this.onStart = onStart;
  55. this.onTerm = onTerm;
  56. Tokenizer t = new Tokenizer();
  57. InputStream[] streams = new InputStream[path.length];
  58. for(int i = 0; i < streams.length; i++)
  59. {
  60. try
  61. {
  62. streams[i] = new FileInputStream(path[i]);
  63. }
  64. catch(FileNotFoundException ex)
  65. {
  66. throw new PreScriptException(ex.getMessage(), -1);
  67. }
  68. }
  69. Compiler c = new Compiler();
  70. this.code = c.compile(t.tokenize(streams), labels, vars, functions, localLabels);
  71. /*int i = 0;
  72. for(Instruction in : code)
  73. {
  74. System.out.printf("%3d: %5b | %s\n", i, in.shouldNotReturnValue(), in);
  75. i++;
  76. }*/
  77. /*this.parser = parser;
  78. this.logger = parser.getLogger();
  79. this.scheduler = parser.getScheduler();
  80. this.labels = new HashMap<>();
  81. this.returnStack = new Stack<>();
  82. this.events = new HashSet<>();
  83. this.currentLine = 0;
  84. this.isWaiting = false;
  85. this.isHolded = false;
  86. this.isValid = true;
  87. this.receiveEventBroadcast = receiveEventBroadcast;
  88. this.cpuTime = 0;
  89. this.catchLine = -1;
  90. this.currentCommand = null;
  91. this.ifState = true;
  92. this.printStackTrace = false;
  93. this.simpleName = simpleName;
  94. this.name = name;
  95. this.id = id;
  96. this.onStart = onStart;
  97. this.onTerm = onTerm;
  98. this.localVars = new Stack<>();
  99. this.functions = new HashMap<>();
  100. this.localLabels = new HashMap<>();
  101. this.code = OldCompiler.compile(this, code, labels, functions, localLabels);*/
  102. }
  103. private void pushIfNotNull(InputProvider in)
  104. {
  105. if(in != null)
  106. {
  107. dataStack.push(in);
  108. }
  109. }
  110. public void run()
  111. {
  112. isWaiting = false;
  113. //System.out.println("_________________________");
  114. long endTime = System.nanoTime() + 15_000_000;
  115. int count = 0;
  116. while(lineIndex < code.length && !isWaiting && !isHolded)
  117. {
  118. try
  119. {
  120. Instruction instr = code[lineIndex];
  121. //System.out.println("EXECUTE: " + instr + " " + dataStack);
  122. if(instr.getArguments() > 0)
  123. {
  124. InputProvider[] args = InputProviderArrayPool.get(instr.getArguments());
  125. for(int i = args.length - 1; i >= 0; i--)
  126. {
  127. args[i] = dataStack.pop();
  128. }
  129. pushIfNotNull(instr.execute(this, args));
  130. }
  131. else
  132. {
  133. pushIfNotNull(instr.execute(this, new InputProvider[0]));
  134. }
  135. //System.out.println("AFTER EXECUTE: " + dataStack);
  136. lineIndex++;
  137. }
  138. catch(Exception ex)
  139. {
  140. if(stackTrace)
  141. {
  142. ex.printStackTrace();
  143. }
  144. if(errorLine != -1)
  145. {
  146. int elements = stackElements.pop();
  147. while(dataStack.size() > elements)
  148. {
  149. dataStack.pop();
  150. }
  151. lineIndex = errorLine + 1;
  152. errorLine = -1;
  153. continue;
  154. }
  155. sm.getLogger().print(ex.getLocalizedMessage(), ex,
  156. code[lineIndex].getName(), name, this, code[lineIndex].getLine());
  157. break;
  158. }
  159. count++;
  160. if(System.nanoTime() > endTime)
  161. {
  162. isHolded = true;
  163. sm.getScheduler().scheduleTask(() ->
  164. {
  165. if(!shouldTerm())
  166. {
  167. isHolded = false;
  168. run();
  169. }
  170. }, 1);
  171. break;
  172. }
  173. }
  174. //System.out.println(count + " " + (15_000_000 / count));
  175. if(shouldTerm() && !dataStack.isEmpty())
  176. {
  177. sm.getLogger().print(String.format("data stack is not empty %s", dataStack));
  178. }
  179. }
  180. public String getName()
  181. {
  182. return name;
  183. }
  184. public int getId()
  185. {
  186. return id;
  187. }
  188. public int getActiveSourceLine()
  189. {
  190. if(lineIndex >= 0 && lineIndex < code.length)
  191. {
  192. return code[lineIndex].getLine();
  193. }
  194. return -1;
  195. }
  196. public ScriptManager getScriptManager()
  197. {
  198. return sm;
  199. }
  200. private HashMap<String, Integer> getLabels()
  201. {
  202. return inFunction.isEmpty() ? labels : localLabels.get(inFunction.peek());
  203. }
  204. public void gotoLabel(String label, boolean error, int add)
  205. {
  206. lineIndex = getLabels().getOrDefault(label, error ? null : lineIndex) + add;
  207. }
  208. public void gotoLabel(String label, boolean error)
  209. {
  210. gotoLabel(label, error, 0);
  211. }
  212. public void goSub(String label)
  213. {
  214. int line = getLabels().get(label);
  215. returnStack.push(lineIndex);
  216. lineIndex = line;
  217. returnVarPop.push(false);
  218. }
  219. public void jumpTo(int jump)
  220. {
  221. lineIndex = jump;
  222. }
  223. public void setIfState(boolean state)
  224. {
  225. ifState.pop();
  226. ifState.push(state);
  227. }
  228. public boolean getIfState()
  229. {
  230. return ifState.peek();
  231. }
  232. public void setErrorLine(int line)
  233. {
  234. errorLine = line;
  235. if(line != -1)
  236. {
  237. stackElements.push(dataStack.size());
  238. }
  239. }
  240. public void handleFunction(String function, InputProvider[] in) throws Exception
  241. {
  242. Integer sub = functions.get(function);
  243. if(sub == null)
  244. {
  245. throw new IllegalArgumentException(String.format("function '%s' does not exist", function));
  246. }
  247. UserFunction uf = (UserFunction) code[sub];
  248. String[] args = uf.getArgumentNames();
  249. HashMap<String, Variable> lvars = new HashMap<>();
  250. if(in.length != args.length)
  251. {
  252. throw new IllegalArgumentException(String.format("invalid number of arguments at function '%s'", function));
  253. }
  254. for(int i = 0; i < in.length; i++)
  255. {
  256. Variable v = new Variable(args[i]);
  257. v.set(this, in[i].get(this));
  258. lvars.put(args[i], v);
  259. }
  260. ifState.push(true);
  261. localVars.push(lvars);
  262. returnStack.push(lineIndex);
  263. lineIndex = sub;
  264. inFunction.push(function);
  265. returnVarPop.push(true);
  266. }
  267. public void handleReturn(ReturnWrapper wrapper)
  268. {
  269. lineIndex = returnStack.pop();
  270. if(returnVarPop.pop())
  271. {
  272. ifState.pop();
  273. inFunction.pop();
  274. localVars.pop();
  275. if(wrapper != null && !code[lineIndex].shouldNotReturnValue())
  276. {
  277. dataStack.add(wrapper);
  278. }
  279. }
  280. }
  281. public Variable getOrAddLocalVariable(String name)
  282. {
  283. HashMap<String, Variable> map = localVars.peek();
  284. Variable v = map.get(name);
  285. if(v != null)
  286. {
  287. return v;
  288. }
  289. v = new Variable(name);
  290. map.put(name, v);
  291. return v;
  292. }
  293. public InputProvider peekDataStack()
  294. {
  295. return dataStack.peek();
  296. }
  297. public void setEventBroadcast(boolean eventBroadcast)
  298. {
  299. this.eventBroadcast = eventBroadcast;
  300. }
  301. public boolean shouldReceiveEventBroadcast()
  302. {
  303. return eventBroadcast;
  304. }
  305. public void term()
  306. {
  307. lineIndex = code.length;
  308. }
  309. public boolean shouldTerm()
  310. {
  311. return lineIndex < 0 || lineIndex >= code.length;
  312. }
  313. public void onTerm()
  314. {
  315. if(onTerm != null)
  316. {
  317. onTerm.accept(this);
  318. }
  319. closeables.forEach(c ->
  320. {
  321. sm.getLogger().print("prepared statement not closed", null, null, name, this, -1);
  322. try
  323. {
  324. c.close();
  325. }
  326. catch(Exception ex)
  327. {
  328. sm.getLogger().print("cannot close closeable in script", ex, null, name, this, -1);
  329. }
  330. });
  331. }
  332. public void onStart()
  333. {
  334. if(onStart != null)
  335. {
  336. onStart.accept(this);
  337. }
  338. }
  339. public void setHolded(boolean b)
  340. {
  341. isHolded = b;
  342. }
  343. public boolean isHolded()
  344. {
  345. return isHolded;
  346. }
  347. public void setWaiting()
  348. {
  349. isWaiting = true;
  350. }
  351. public boolean isWaiting()
  352. {
  353. return isWaiting;
  354. }
  355. public void setVar(String name, Object value)
  356. {
  357. Variable v = vars.get(name);
  358. if(v != null)
  359. {
  360. v.set(this, value);
  361. }
  362. }
  363. public Variable getVar(String name)
  364. {
  365. return vars.get(name);
  366. }
  367. public boolean isEventLoaded(String event)
  368. {
  369. return loadedEvents.contains(event);
  370. }
  371. public boolean loadEvent(String event)
  372. {
  373. return loadedEvents.add(event);
  374. }
  375. public boolean unloadEvent(String event)
  376. {
  377. return loadedEvents.remove(event);
  378. }
  379. public void setStackTrace(boolean b)
  380. {
  381. stackTrace = b;
  382. }
  383. public synchronized void addCloseable(AutoCloseable closeable)
  384. {
  385. closeables.add(closeable);
  386. }
  387. public synchronized void removeCloseable(AutoCloseable closeable)
  388. {
  389. closeables.remove(closeable);
  390. }
  391. @Override
  392. public int hashCode()
  393. {
  394. return id;
  395. }
  396. @Override
  397. public boolean equals(Object o)
  398. {
  399. return o != null && o instanceof Script && ((Script) o).id == id;
  400. }
  401. }