package parser;

/**
 * Factory for T grammar non-terminal objects.
 */
public class TFact extends ATVFactory {
    /**
     * Factory to parse T1 grammar non-terminals.
     */
    private T1Fact _t1Fact;

    /**
     * Token visitor to parse T1 grammar non-terminals.
     */
    private ITokVisitor _parseT1;

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

            // initialize
            _parseT1 = _t1Fact.makeVisitor();
            return null;
        }
    };

    /**
     * Constructor for the T factory,
     *
     * @param tkz   tokenizer to use
     * @param t1Fac factory for T1 non-terminals
     */
    public TFact(ITokenizer tkz, T1Fact t1Fac) {
        super(tkz);
        _t1Fact = t1Fac;
    }

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

    /**
     * Make an T grammar non-terminal.
     *
     * @param host number token
     * @param inp  visitor-specific input
     * @return T grammar non-terminal
     */
    private T makeT(NumToken host, Object inp) {
        return new T(host, (T1) nextToken().execute(_parseT1, inp));
    }

    /**
     * Make a token visitor to parse an T non-terminal.
     *
     * @return token visitor
     */
    public ITokVisitor makeVisitor() {
        initialize();
        return new NumToken.INumVisitor() {
            public Object numCase(NumToken host, Object inp) {
                return makeT(host, inp);
            }

            public Object defaultCase(AToken host, Object param) {
                throw new IllegalArgumentException("Wrong token: '" + host + "'");
            }
        };
    }

    /**
     * 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(ITokVisitor successor) {
        initialize();
        return new NumToken.AChainVis(successor) {
            public Object numCase(NumToken host, Object inp) {
                return makeT(host, inp);
            }
        };
    }
}

