001package org.clafer.ir; 002 003import java.util.Arrays; 004import org.clafer.common.Check; 005import org.clafer.domain.Domain; 006 007/** 008 * 009 * @author jimmy 010 */ 011public abstract class IrAbstractString implements IrStringExpr { 012 013 private final Domain[] charDomains; 014 private final Domain lengthDomain; 015 private final boolean isConstant; 016 017 IrAbstractString(Domain[] charDomains, Domain lengthDomain) { 018 this.charDomains = Check.noNulls(charDomains); 019 this.lengthDomain = Check.notNull(lengthDomain); 020 021 for (Domain c : charDomains) { 022 if (c.getLowBound() < Character.MIN_VALUE) { 023 throw new IllegalStringException(); 024 } 025 if (c.getHighBound() > Character.MAX_VALUE) { 026 throw new IllegalStringException(); 027 } 028 } 029 for (int i = 0; i < charDomains.length && i < lengthDomain.getLowBound(); i++) { 030 if (charDomains[i].isConstant() && charDomains[i].getLowBound() == 0) { 031 throw new IllegalStringException(); 032 } 033 } 034 for (int i = lengthDomain.getHighBound(); i < charDomains.length; i++) { 035 if (!charDomains[i].contains(0)) { 036 throw new IllegalStringException(); 037 } 038 } 039 if (lengthDomain.isEmpty()) { 040 throw new IllegalStringException(); 041 } 042 if (lengthDomain.getLowBound() < 0) { 043 throw new IllegalStringException(); 044 } 045 if (lengthDomain.getHighBound() > charDomains.length) { 046 throw new IllegalStringException(); 047 } 048 assert lengthDomain.getHighBound() == charDomains.length : "Correct but not optimized."; 049 this.isConstant = lengthDomain.isConstant() && Arrays.asList(charDomains).stream().allMatch(Domain::isConstant); 050 } 051 052 @Override 053 public Domain[] getChars() { 054 return charDomains; 055 } 056 057 @Override 058 public Domain getLength() { 059 return lengthDomain; 060 } 061 062 @Override 063 public boolean isConstant() { 064 return isConstant; 065 } 066 067 @Override 068 public boolean equals(Object obj) { 069 if (obj instanceof IrAbstractString) { 070 IrAbstractString other = (IrAbstractString) obj; 071 return Arrays.equals(charDomains, other.charDomains) 072 && lengthDomain.equals(other.lengthDomain); 073 } 074 return false; 075 } 076 077 @Override 078 public int hashCode() { 079 return Arrays.hashCode(charDomains) ^ lengthDomain.hashCode(); 080 } 081}