package accrue.analysis.ext;

import java.util.Map;

import polyglot.ast.Conditional;
import polyglot.ast.Expr;
import polyglot.util.SerialVersionUID;
import polyglot.visit.DataFlow;
import polyglot.visit.FlowGraph;
import polyglot.visit.FlowGraph.EdgeKey;
import polyglot.visit.FlowGraph.Peer;
import accrue.analysis.interprocanalysis.DataFlowDispatch;
import accrue.analysis.pointer.RegisterPointerStmtsVisitor;
import accrue.analysis.pointer.StmtRegistrar;

public class ExtConditional extends ExtExpr {
    private static final long serialVersionUID = SerialVersionUID.generate();

    @Override
    public void registerPointerStmts(StmtRegistrar registrar,
            RegisterPointerStmtsVisitor v) {
        Expr e = (Expr) this.node();
        if (!e.type().isReference()) return;

        Conditional c = (Conditional) e;
        if (v.recordExprResults()) {
            registrar.createFreshReferenceVariable(c, v.constructorContext());

            registrar.addAssignment(v.getReferenceVariable(e),
                                    v.getReferenceVariable(c.consequent()),
                                    c.position(),
                                    v.currentCode());
            registrar.addAssignment(v.getReferenceVariable(e),
                                    v.getReferenceVariable(c.alternative()),
                                    c.position(),
                                    v.currentCode());
        }
    }

    @Override
    public int numArgumentsOnResultStack() {
        return 2;
    }

    @Override
    public <DFItem extends DataFlow.Item> Map<EdgeKey, DFItem> flowDispatch(
            DataFlowDispatch<DFItem> dataflow, DFItem dfIn,
            FlowGraph<DFItem> graph, Peer<DFItem> peer) {
        Conditional n = (Conditional) this.node();
        return dataflow.flowConditional(n, dfIn, graph, peer);
    }

}
