package accrue.analysis.pointer;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import polyglot.frontend.ExtensionInfo;
import polyglot.main.Report;
import polyglot.types.ProcedureInstance;
import accrue.AccrueOptionsHelper;
import accrue.analysis.AnalysisTopics;
import accrue.analysis.pointer.analyses.HeapAbstractionFactory;

public class PointsToEngineTimeout extends PointsToEngine {
    private List<PointsToEngine> engines;
    private PointsToEngine successfulEngine = null;

    public PointsToEngineTimeout(String hafString) {
        super();
        engines = new ArrayList<PointsToEngine>();
        // go through and create a list of engines with different
        // abstractions
        StringTokenizer st = new StringTokenizer(hafString, ":");
        while (st.hasMoreTokens()) {
            String s = st.nextToken();
            HeapAbstractionFactory haf =
                    AccrueOptionsHelper.createHeapAbstractionFactory(s);
            engines.add(new PointsToEngineSingleThread(haf));
        }
    }

    @Override
    public HeapAbstractionFactory heapAbstractionFactory() {
        return successfulEngine.heapAbstractionFactory();
    }

    @Override
    public PointsToGraph solveImpl(StmtRegistrar registrar,
            ExtensionInfo extInfo) {
        // Note that we never call this.checkTimeout, as we do not check the 
        // timeout for this engine. We only check timeout for the engines in the list.
        for (PointsToEngine eng : engines) {
            eng.setTimeout(this.timeout());
            try {
                PointsToGraph g = eng.solve(registrar, extInfo);
                successfulEngine = eng;
                return g;
            }
            catch (PointsToTimeoutException e) {
                // The engine timed out. Try the next one
                System.err.println("Timed out after " + this.timeout()
                        + "ms on engine " + eng);
                if (Report.should_report(AnalysisTopics.POINTSTO, 1)) {
                    Report.report(1, "Timed out after " + this.timeout()
                            + "ms on engine " + eng);
                }
            }
        }
        throw new PointsToTimeoutException();
    }

    @Override
    public String toString() {
        return this.getClass().getSimpleName() + " with timeout list "
                + this.engines;
    }

    @Override
    void recordRead(StmtAndContext sac, PointsToGraphNode r) {
        throw new UnsupportedOperationException();
    }

    @Override
    void newContext(ProcedureInstance callee, CContext calleeContext) {
        throw new UnsupportedOperationException();
    }

    @Override
    void changedNode(PointsToGraphNode n) {
        throw new UnsupportedOperationException();
    }

}
