package accrue.analysis.goals;

import java.util.HashMap;
import java.util.Map;

import polyglot.ast.Node;
import polyglot.frontend.CyclicDependencyException;
import polyglot.frontend.ExtensionInfo;
import polyglot.frontend.Job;
import polyglot.frontend.Scheduler;
import polyglot.frontend.goals.Barrier;
import polyglot.frontend.goals.Goal;
import polyglot.frontend.goals.VisitorGoal;
import polyglot.types.FieldInstance;
import polyglot.util.InternalCompilerError;
import accrue.AccrueScheduler;
import accrue.analysis.visit.RegisterFieldDecls;

public class RegisterDeclsGoal extends Barrier {
    protected Map<FieldInstance, Node> decls;

    protected RegisterDeclsGoal(Scheduler scheduler) {
        super(scheduler);
        this.decls = new HashMap<FieldInstance, Node>();
    }

    public Map<FieldInstance, Node> decls() {
        return decls;
    }

    @Override
    public Goal goalForJob(Job job) {
        Goal g =
                scheduler.internGoal(new VisitorGoal(job,
                                                     new RegisterFieldDecls(decls)));
        AccrueScheduler sched = (AccrueScheduler) scheduler;
        try {
            g.addPrerequisiteGoal(sched.helper().RegisterPointerStmts(job),
                                  scheduler);
        }
        catch (CyclicDependencyException e) {
            throw new InternalCompilerError(e);
        }
        return g;
    }

    public static RegisterDeclsGoal singleton(ExtensionInfo extInfo) {
        Scheduler scheduler = extInfo.scheduler();
        return (RegisterDeclsGoal) scheduler.internGoal(new RegisterDeclsGoal(scheduler));
    }

}
