package code.type.typechecker;

import code.type.TypeExpression;
import code.type.TypeVariable;

import java.util.Hashtable;

/**
 * Models an environment in which type checking/inference is performed.
 * Maintains the binding for TypeVariable names to TypeExpression in the data member substitution.
 * Maintains a counter (nextid) to generate the next name for a type variable.
 *
 * @author Pravin Damle
 * @since 12/2/04
 */
public class Environment {

    // map a type variable name to its substitution
    private final Hashtable substitution;

    private int nextid = 0;

    // constructors
    public Environment() {
        substitution = new Hashtable();
    }

    public String generateName() {
        nextid++;
        return "" + nextid;
//        return "_" + nextid;
    }
    public String getNextId() { return ""+nextid; }

    // substitution related methods.
    public TypeExpression getSubst(String name) {
        TypeExpression exp = (TypeExpression) substitution.get(name);
        return exp;
    }

    public void setSubst(TypeVariable tv, TypeExpression expr) {
        if (!substitution.containsKey(tv.name)) {
            // establish the substitution
            substitution.put(tv.name, expr);
        } else {
            throw new RuntimeException("Substitution for " + tv.name + " already established");
        }
    }

}

