Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package org.cfml.util;
- import java.util.*;
- import java.util.regex.*;
- import org.cfml.Code;
- import org.cfml.instr.Instruction;
- public class InstructionFinder {
- private Code code;
- private int position = 0;
- public InstructionFinder(Code c) {
- code = c;
- }
- public void setCode(Code c) {
- code = c;
- position = 0;
- }
- public Code code() {
- return code;
- }
- public Instruction[][] find(String regex) {
- return find(regex, null);
- }
- public Instruction[][] find(String regex, MatchVerifier mv) {
- Instruction[] instructions = code.instructions();
- StringBuffer sb = new StringBuffer();
- if(instructions.length > 0) {
- sb.append(instructions[0].name());
- for(int i = 1; i < instructions.length; i++)
- sb.append(' ' + instructions[i].name());
- }
- Matcher m = Pattern.compile(regex).matcher(sb);
- List<Instruction[]> matches = new Vector<Instruction[]>();
- int found = 0;
- while(m.find()) {
- if(m.start() != 0 && sb.charAt(m.start() - 1) != ' ')
- continue;
- int start = sb.substring(0, m.start()).split(" ").length;
- if(m.start() == 0 && start == 1)
- start = 0;
- Instruction[] match = new Instruction[sb.substring(0, m.end()).split(" ").length - start];
- System.arraycopy(instructions, start, match, 0, match.length);
- if(mv != null && !mv.verify(match))
- continue;
- matches.add(match);
- found++;
- }
- return matches.toArray(new Instruction[found][]);
- }
- public Instruction[] findNext(String regex) {
- return findNext(regex, null);
- }
- public Instruction[] findNext(String regex, MatchVerifier mv) {
- Instruction[] instructions = code.instructions();
- StringBuffer sb = new StringBuffer();
- if(instructions.length > position) {
- sb.append(instructions[position].name());
- for(int i = position + 1; i < instructions.length; i++)
- sb.append(' ' + instructions[i].name());
- }
- Matcher m = Pattern.compile(regex).matcher(sb);
- while(m.find()) {
- if(m.start() != 0 && sb.charAt(m.start() - 1) != ' ')
- continue;
- int start = sb.substring(0, m.start()).split(" ").length;
- if(m.start() == 0 && start == 1)
- start = 0;
- Instruction[] match = new Instruction[sb.substring(0, m.end()).split(" ").length - start];
- System.arraycopy(instructions, position + start, match, 0, match.length);
- if(mv != null && !mv.verify(match))
- continue;
- position = position + start + match.length;
- return match;
- }
- return null;
- }
- public static interface MatchVerifier {
- public boolean verify(Instruction[] match);
- }
- }
Add Comment
Please, Sign In to add comment