Compiles regular expressions into PikeVMs. @author Johannes Schindelin
| 19 | * @author Johannes Schindelin |
| 20 | */ |
| 21 | class Compiler implements PikeVMOpcodes { |
| 22 | private final static CharacterMatcher regularCharacter = |
| 23 | CharacterMatcher.parse("[^\\\\.*+?|\\[\\]{}()^$]"); |
| 24 | |
| 25 | private static class Output { |
| 26 | private int[] program; |
| 27 | private int offset; |
| 28 | private int groupCount = -1; |
| 29 | private int findPreambleSize; |
| 30 | private ArrayList<CharacterMatcher> classes; |
| 31 | private ArrayList<PikeVM> lookarounds; |
| 32 | |
| 33 | public Output(Expression expr) { |
| 34 | // try-run to determine the code size |
| 35 | expr.writeCode(this); |
| 36 | program = new int[offset]; |
| 37 | offset = 0; |
| 38 | groupCount = -1; |
| 39 | classes = new ArrayList<CharacterMatcher>(); |
| 40 | lookarounds = new ArrayList<PikeVM>(); |
| 41 | // write it out! |
| 42 | expr.writeCode(this); |
| 43 | } |
| 44 | |
| 45 | public void add(int opcode) { |
| 46 | if (program != null) { |
| 47 | program[offset] = opcode; |
| 48 | } |
| 49 | offset++; |
| 50 | } |
| 51 | |
| 52 | public int markJump() { |
| 53 | return offset++; |
| 54 | } |
| 55 | |
| 56 | public void setJump(int mark) { |
| 57 | if (program != null) { |
| 58 | program[mark] = offset; |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | public void markFindPreambleEnd() { |
| 63 | findPreambleSize = offset; |
| 64 | } |
| 65 | |
| 66 | public PikeVM toVM() { |
| 67 | CharacterMatcher[] classes = new CharacterMatcher[this.classes.size()]; |
| 68 | this.classes.toArray(classes); |
| 69 | PikeVM[] lookarounds = new PikeVM[this.lookarounds.size()]; |
| 70 | this.lookarounds.toArray(lookarounds); |
| 71 | return new PikeVM(program, findPreambleSize, groupCount, classes, |
| 72 | lookarounds); |
| 73 | } |
| 74 | |
| 75 | public int addClass(CharacterMatcher characterClass) { |
| 76 | if (program == null) { |
| 77 | return -1; |
| 78 | } |