studio.qeditor.syntax.SyntaxStateMachine Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kdbStudio Show documentation
Show all versions of kdbStudio Show documentation
Studio for kdb+ is a rapid development environment for the ultra-fast database kdb+ from Kx Systems: http://www.kx.com.
package studio.qeditor.syntax;
import java.util.*;
public class SyntaxStateMachine {
private Transition[] transitions;
private final List rules = new ArrayList<>();
private final static int MAX_CHAR=128;
//Action.Match: the token is finished on current character
//Action.MatchPrev: with the current character, now we know that token finished on previous character
//Action.LooksLike: we are in the middle of token. If it is the last character in the system, we return the token which might be not finished
public enum Action {LooksLike, Match, MatchPrev};
public SyntaxStateMachine() {
}
public void add(Enum fromState, String chars, Enum nextState, QToken token, Action action) {
rules.add(new Rule(fromState, chars, nextState, token, action));
}
public String getChars(Enum state) {
StringBuilder chars = new StringBuilder();
for (Rule rule:rules) {
if (rule.fromState != state) continue;
chars.append(rule.chars);
}
return chars.toString();
}
public void init() {
validateStateMachine();
transitions = new Transition[getAllStates().length];
for (int index = 0; index< transitions.length; index++) {
transitions[index] = new Transition();
}
for(Rule rule: rules) {
Transition transition = transitions[rule.fromState.ordinal()];
if (rule.chars.length() == 0) {
if (transition.defaultNextState != null) {
throw new IllegalStateException("Wrong state machine: duplicate default rule for " + rule.fromState);
}
transition.defaultNextState = rule.next;
} else {
for (char ch: rule.chars.toCharArray()) {
if (transition.nextState[ch] != null) {
throw new IllegalStateException("Wrong state machine: duplicate rule for " + rule.fromState + "; char " + ch);
}
transition.nextState[ch] = rule.next;
}
}
}
}
public Next getNext(Enum state, char ch) {
Transition transition = transitions[state.ordinal()];
if (ch allStates = new HashSet<>(Arrays.asList(getAllStates()));
Set fromStates = new HashSet<>(allStates);
Set nextStates = new HashSet<>(allStates);
for (Rule rule:rules) {
fromStates.remove(rule.fromState);
nextStates.remove(rule.next.nextState);
}
if (fromStates.size()>0) {
throw new IllegalStateException("Wrong state machine: from states missing: " + fromStates);
}
if (nextStates.size()>0) {
throw new IllegalStateException("Wrong state machine: from states missing: " + nextStates);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy