001package org.clafer.ast.analysis;
002
003import java.util.Collections;
004import java.util.Set;
005import org.clafer.ast.AstClafer;
006import org.clafer.ast.AstUtil;
007
008/**
009 *
010 * @author jimmy
011 */
012public class Type {
013
014    private final Set<AstClafer> unionType;
015    private final AstClafer commonSuperType;
016
017    public Type(Set<AstClafer> unionType, AstClafer commonSupertype) {
018        if (unionType.isEmpty()) {
019            throw new IllegalArgumentException();
020        }
021        this.unionType = unionType;
022        this.commonSuperType = commonSupertype;
023    }
024
025    public Type(Set<AstClafer> unionType) {
026        if (unionType.isEmpty()) {
027            throw new IllegalArgumentException();
028        }
029        this.unionType = unionType;
030        this.commonSuperType = AstUtil.getLowestCommonSupertype(unionType);
031    }
032
033    public Set<AstClafer> getUnionType() {
034        return unionType;
035    }
036
037    public AstClafer getCommonSuperType() {
038        return commonSuperType;
039    }
040
041    public boolean isBasicType() {
042        return unionType.size() == 1;
043    }
044
045    public AstClafer getBasicType() {
046        assert isBasicType();
047        return unionType.iterator().next();
048    }
049
050    public static Type basicType(AstClafer type) {
051        return new Type(Collections.singleton(type));
052    }
053
054    @Override
055    public boolean equals(Object obj) {
056        if (obj instanceof Type) {
057            Type other = (Type) obj;
058            return unionType.equals(other);
059        }
060        return false;
061    }
062
063    @Override
064    public int hashCode() {
065        return unionType.hashCode();
066    }
067
068    @Override
069    public String toString() {
070        return unionType.size() == 1 ? commonSuperType.toString() : unionType.toString();
071    }
072}