DFAState.java 1.6 KB
Newer Older
R
Richard Gong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
package play.parser;

import java.util.Collections;
import java.util.Set;

/**
 * DFA的状态。
 * 每个DFN包含多个NFA。
 */
public class DFAState extends State {

    //组成这个DFAState的NFAState的集合
    private Set<State> states = null;


    public DFAState(Set<State> states) {
        this.states = states;
    }


    protected Set<State> states(){
        return Collections.unmodifiableSet(states);
    }

    /**
R
Richard Gong 已提交
26 27
     * 提供一个对象作为迁移条件,看能否迁移到下一个状态
     * @param obj,做词法分析
R
Richard Gong 已提交
28 29
     * @return
     */
R
Richard Gong 已提交
30
    protected DFAState getNextState(Object obj) {
R
Richard Gong 已提交
31
        for (Transition transition : transitions()) {
R
Richard Gong 已提交
32
            if (transition.match(obj)) {
R
Richard Gong 已提交
33 34 35 36 37 38 39 40 41
                return (DFAState) getState(transition);
            }
        }
        return null;
    }

    @Override
    public String toString() {
        String rtn = super.toString();
R
Richard Gong 已提交
42
        rtn += "\tNFA states: ";
R
Richard Gong 已提交
43 44 45 46 47 48 49 50 51 52
        int i = 0;
        for (State state : states) {
            if (i++ > 0) {
                rtn += ", ";
            }
            rtn += state.getName();
            if (state.getGrammarNode() != null && state.getGrammarNode().isNamedNode()) {
                rtn += "(" + state.getGrammarNode().getName() + ")";
            }
        }
R
Richard Gong 已提交
53
        rtn += "\n";
R
Richard Gong 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
        return rtn;
    }

    /**
     * 只要它所包含的NFA有一个是接受状态,该DFAState就是接受状态。
     * @return
     */
    @Override
    public boolean isAcceptable() {
        for (State state : states) {
            if (state.isAcceptable()) {
                return true;
            }
        }
        return false;
    }

}