package parser;

/**
 * Factory for E grammar non-terminal objects.
 */
public class EFact extends ATVFactory {
    /**
     * Factory for F grammar non-terminals.
     */
    private FFact _fFact;

    /**
     * Visitor for F grammar non-terminals.
     */
    private ITokVisitor _parseF;

    /**
     * Factory for E1 grammar non-terminals.
     */
    private E1Fact _e1Fact;

    /**
     * Visitor for E1 grammar non-terminals.
     */
    private ITokVisitor _parseE1;

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

            // initialize
            _parseF = _fFact.makeVisitor();
            _parseE1 = _e1Fact.makeVisitor();
            return null;
        }
    };

    /**
     * Constructor for the E factory,
     *
     * @param tkz    tokenizer to use
     * @param fFact  factory for F non-terminals
     * @param e1Fact factory for E1 non-terminals
     */
    public EFact(ITokenizer tkz, FFact fFact, E1Fact e1Fact) {
        super(tkz);
        _fFact = fFact;
        _e1Fact = e1Fact;
    }

    /**
     * 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 param) {
                return new E((F) host.execute(_parseF, param), (E1) nextToken().execute(_parseE1, param));
            }
        };
    }

    /**
     * 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(_fFact.makeChainedVisitor(successor), inp);
                return (o instanceof F) ? new E((F) o, (E1) nextToken().execute(_parseE1, inp)) : o;
            }
        };
    }

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

