package parser;

/**
 * Factory for E grammar non-terminal objects.
 */
public class EFact extends ATVFactory {
    /**
     * Factory to parse E1 grammar non=terminals.
     */
    private E1Fact _e1Fact;

    /**
     * Factory to parse T grammar non=terminals.
     */
    private TFact _tFact;

    /**
     * Token visitor to parse E1 grammar non-terminals.
     */
    private ITokVisitor _parseE1;

    /**
     * Token visitor to parse T grammar non-terminals.
     */
    private ITokVisitor _parseT;

    /**
     * Initializer lambda for this factory.
     */
    private ILambda _initializer = new ILambda() {
        public Object apply(Object param) {
            // change state to no-op
            _initializer = NoOpLambda.Singleton;

            // initialize
            _parseE1 = _e1Fact.makeVisitor();
            _parseT = _tFact.makeVisitor();
            return null;
        }
    };

    /**
     * Constructor for the E factory,
     *
     * @param tkz    tokenizer to use
     * @param e1Fact factory for E1 non-terminals
     * @param tFact  factory for T non-terminals
     */
    public EFact(ITokenizer tkz, E1Fact e1Fact, TFact tFact) {
        super(tkz);
        _e1Fact = e1Fact;
        _tFact = tFact;
    }

    /**
     * Make visitors.
     */
    private void initialize() {
        _initializer.apply(null);
    }

    /**
     * Make a token visitor to parse an E non-terminal.
     *
     * @return token visitor
     */
    public ITokVisitor makeVisitor() {
        initialize();
        return new ITokVisitor() {
            public Object defaultCase(AToken host, Object inp) {
                return new E((T) host.execute(_parseT, inp), (E1) nextToken().execute(_parseE1, inp));
            }
        };
    }

    /**
     * Make a token visitor that delegates to the given visitor in a chain of responsibility.
     *
     * @param successor visitor to serve as successor in the chain
     */
    public ITokVisitor makeChainedVisitor(final ITokVisitor successor) {
        initialize();
        return new ITokVisitor() {
            public Object defaultCase(AToken host, Object inp) {
                Object o = host.execute(_tFact.makeChainedVisitor(successor), inp);
                return (o instanceof T) ? new E((T) o, (E1) nextToken().execute(_parseE1, inp)) : o;
            }
        };
    }
}

