Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static Token[] thompsonVM (Instruction[] program, String input) {
- int inputLength, beginIndex;
- char currentCharacter;
- ArrayList<Integer> currentList, nextList;
- ArrayList<Token> returnTokens;
- Token matchedToken;
- String currentMatchedString = "";
- beginIndex = 0; //used to save the current match as a substring of the input
- inputLength = input.length(); //stored for slightly quicker runtime
- currentList = new ArrayList<>(); //current list of threads as integers (line number in the program)
- nextList = new ArrayList<>(); //next list of threads
- returnTokens = new ArrayList<>(); //list of matched strings in the form ID:'value'
- matchedToken = new Token("", ""); //the current matched token
- currentList.add(0); //start the program with a single thread at instruction 0
- for (int characterIndex = 0; characterIndex <= inputLength; characterIndex++) {
- if (characterIndex != inputLength) {
- currentCharacter = input.charAt(characterIndex);
- } else {
- currentCharacter = 0; //if past the last character, set to null
- }
- for (int currentInstruction, instructionIndex = 0; instructionIndex < currentList.size(); instructionIndex++) { //for all instructions in currentList
- currentInstruction = currentList.get(instructionIndex);
- switch (program[currentInstruction].opCode) {
- case CHAR:
- CharInstruction charInst = (CharInstruction)program[currentInstruction];
- if (!(currentCharacter >= charInst.lowerLimit && currentCharacter <= charInst.upperLimit)) {
- } else {
- nextList.add(currentInstruction + 1);
- System.out.println("Matched char " + currentCharacter);
- }
- break;
- case MATCH:
- MatchInstruction matchInst = (MatchInstruction)program[currentInstruction];
- currentMatchedString = (input.substring(beginIndex, characterIndex));
- if (currentMatchedString.length() > matchedToken.getValue().length()) {
- matchedToken.setID(matchInst.tokenID);
- matchedToken.setValue(currentMatchedString);
- }
- System.out.println("Matched word " + currentMatchedString);
- continue;
- case JMP:
- JmpInstruction jmpInst = (JmpInstruction)program[currentInstruction];
- currentList.add(jmpInst.jumpTo);
- break;
- case SPLIT:
- SplitInstruction splitInst = (SplitInstruction)program[currentInstruction];
- currentList.add(splitInst.firstJump);
- currentList.add(splitInst.secondJump);
- break;
- }
- }
- currentList.clear();
- currentList.addAll(nextList);
- nextList.clear();
- if (currentList.isEmpty() && !matchedToken.getValue().isEmpty()) { //if all threads died
- currentList.add(0);
- returnTokens.add(matchedToken);
- matchedToken = new Token("", "");
- beginIndex = characterIndex + 1;
- }
- }
- Token[] returnArray = new Token[returnTokens.size()];
- returnTokens.toArray(returnArray);
- return returnArray;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement