Add ATN optimization to remove null state entries and renumber the remaining states

This commit is contained in:
Sam Harwell 2012-07-31 13:30:27 -05:00
parent f9bacf5060
commit 1f4df2ea5a
1 changed files with 27 additions and 0 deletions

View File

@ -31,9 +31,12 @@
package org.antlr.v4.automata; package org.antlr.v4.automata;
import org.antlr.v4.runtime.atn.ATN; import org.antlr.v4.runtime.atn.ATN;
import org.antlr.v4.runtime.atn.ATNState;
import org.antlr.v4.runtime.misc.NotNull; import org.antlr.v4.runtime.misc.NotNull;
import org.antlr.v4.tool.Grammar; import org.antlr.v4.tool.Grammar;
import java.util.List;
/** /**
* *
* @author Sam Harwell * @author Sam Harwell
@ -41,6 +44,30 @@ import org.antlr.v4.tool.Grammar;
public class ATNOptimizer { public class ATNOptimizer {
public static void optimize(@NotNull Grammar g, @NotNull ATN atn) { public static void optimize(@NotNull Grammar g, @NotNull ATN atn) {
optimizeStates(atn);
}
private static void optimizeStates(ATN atn) {
List<ATNState> states = atn.states;
int current = 0;
for (int i = 0; i < states.size(); i++) {
ATNState state = states.get(i);
if (state == null) {
continue;
}
if (i != current) {
state.stateNumber = current;
states.set(current, state);
states.set(i, null);
}
current++;
}
System.out.println("ATN optimizer removed " + (states.size() - current) + " null states.");
states.subList(current, states.size()).clear();
} }
private ATNOptimizer() { private ATNOptimizer() {