package com.cp.brainfuck; import java.util.Stack; import java.util.EmptyStackException; import java.util.ArrayList; import com.cp.ircbot.bot.IRCBot; public class BrainfuckInterpreter { private ArrayList threads; private IRCBot bot; public BrainfuckInterpreter(IRCBot bot) { this.bot = bot; threads = new ArrayList(); } public ArrayList cleanup() { ArrayList toRemove = new ArrayList(); ArrayList output = new ArrayList(); for (BrainfuckThread thread : threads) { if (!thread.isRunning()) toRemove.add(thread); } for (BrainfuckThread thread : toRemove) { if (!thread.getOutput().getOutput().equals("")) { output.add(thread.getOutput().getOutput()); } } threads.removeAll(toRemove); return output; } public BrainfuckThread execute(String brainfuck) throws BrainfuckParseError { return execute(brainfuck.toCharArray()); } public BrainfuckThread execute(char[] brainfuck) throws BrainfuckParseError { char[] segments = parse(brainfuck); BrainfuckThread thread = new BrainfuckThread(brainfuck, segments, new BrainfuckWriter()); threads.add(thread); return thread; } private char[] parse(char[] brainfuck) throws BrainfuckParseError { char[] codeStack = new char[brainfuck.length]; Stack stack = new Stack(); for (int index = 0; index < brainfuck.length; index++) { switch (brainfuck[index]) { case '[': stack.push(index); break; case ']': try { int x = stack.pop(); codeStack[x] = (char) index; codeStack[index] = (char) x; } catch (EmptyStackException e) { throw new BrainfuckParseError("Unbalanced brackets"); } break; } } if (!stack.isEmpty()) throw new BrainfuckParseError("Unclosed bracket"); return codeStack; } }