1 21 22 package net.percederberg.grammatica.parser; 23 24 import java.io.IOException ; 25 26 36 class Automaton { 37 38 41 private Object value = null; 42 43 48 private AutomatonTree tree = new AutomatonTree(); 49 50 53 public Automaton() { 54 } 55 56 65 public void addMatch(String str, boolean caseInsensitive, Object value) { 66 Automaton state; 67 68 if (str.equals("")) { 69 this.value = value; 70 } else { 71 state = tree.find(str.charAt(0), caseInsensitive); 72 if (state == null) { 73 state = new Automaton(); 74 state.addMatch(str.substring(1), caseInsensitive, value); 75 tree.add(str.charAt(0), caseInsensitive, state); 76 } else { 77 state.addMatch(str.substring(1), caseInsensitive, value); 78 } 79 } 80 } 81 82 98 public Object matchFrom(LookAheadReader input, 99 int pos, 100 boolean caseInsensitive) 101 throws IOException { 102 103 Object result = null; 104 Automaton state; 105 int c; 106 107 c = input.peek(pos); 108 if (tree != null && c >= 0) { 109 state = tree.find((char) c, caseInsensitive); 110 if (state != null) { 111 result = state.matchFrom(input, pos + 1, caseInsensitive); 112 } 113 } 114 return (result == null) ? value : result; 115 } 116 117 118 127 private class AutomatonTree { 128 129 133 private char value = '\0'; 134 135 138 private Automaton state = null; 139 140 143 private AutomatonTree left = null; 144 145 148 private AutomatonTree right = null; 149 150 153 public AutomatonTree() { 154 } 155 156 168 public Automaton find(char c, boolean lowerCase) { 169 if (lowerCase) { 170 c = Character.toLowerCase(c); 171 } 172 if (value == '\0' || value == c) { 173 return state; 174 } else if (value > c) { 175 return left.find(c, false); 176 } else { 177 return right.find(c, false); 178 } 179 } 180 181 190 public void add(char c, boolean lowerCase, Automaton state) { 191 if (lowerCase) { 192 c = Character.toLowerCase(c); 193 } 194 if (value == '\0') { 195 this.value = c; 196 this.state = state; 197 this.left = new AutomatonTree(); 198 this.right = new AutomatonTree(); 199 } else if (value > c) { 200 left.add(c, false, state); 201 } else { 202 right.add(c, false, state); 203 } 204 } 205 } 206 } 207 | Popular Tags |