Search in sources :

Example 1 with Reduce

use of suite.ebnf.lr.BuildLr.Reduce in project suite by stupidsing.

the class LrParse method parse.

private Ast parse(Source<Ast> tokens, State state) {
    Deque<Pair<Ast, State>> stack = new ArrayDeque<>();
    Ast token = tokens.source();
    while (true) {
        String lookahead = token != null ? token.entity : "EOF";
        Pair<State, Reduce> sr = shift(stack, state, lookahead);
        if (sr.t0 != null) {
            // shift
            stack.push(Pair.of(token, state));
            state = sr.t0;
            token = tokens.source();
        } else {
            // reduce
            Reduce reduce = sr.t1;
            IList<Ast> nodes = IList.end();
            for (int i = 0; i < reduce.n(); i++) {
                Pair<Ast, State> ns = stack.pop();
                nodes = IList.cons(ns.t0, nodes);
                state = ns.t1;
            }
            Ast token1 = new Ast(reduce.name(), 0, 0, Read.from(nodes).toList());
            if (rootEntity.equals(reduce.name()) && stack.size() == 0 && token == null)
                return token1;
            // force shift after reduce
            stack.push(Pair.of(token1, state));
            state = shift(stack, state, token1.entity).t0;
        }
    }
}
Also used : Ast(suite.ebnf.Ebnf.Ast) State(suite.ebnf.lr.BuildLr.State) Reduce(suite.ebnf.lr.BuildLr.Reduce) ArrayDeque(java.util.ArrayDeque) Pair(suite.adt.pair.Pair)

Aggregations

ArrayDeque (java.util.ArrayDeque)1 Pair (suite.adt.pair.Pair)1 Ast (suite.ebnf.Ebnf.Ast)1 Reduce (suite.ebnf.lr.BuildLr.Reduce)1 State (suite.ebnf.lr.BuildLr.State)1