1
package dk.aau.cs.model.tapn;
3
import java.math.BigDecimal;
5
import java.util.regex.Matcher;
6
import java.util.regex.Pattern;
8
import dk.aau.cs.model.tapn.Bound.InfBound;
9
import dk.aau.cs.util.Require;
11
public class TimeInvariant {
12
public static final TimeInvariant LESS_THAN_INFINITY = new TimeInvariant(false, Bound.Infinity);
13
private boolean isUpperIncluded;
16
public TimeInvariant(boolean isUpperIncluded, Bound upper) {
17
Require.that(upper != null, "bound cannot be null");
18
Require.that(isUpperIncluded || (!isUpperIncluded && upper.value() != 0), "\"< 0\" is and invalid invariant.");
19
Require.that(upper != Bound.Infinity || !isUpperIncluded, "\"<=inf\" is not a valid invariant");
21
this.isUpperIncluded = isUpperIncluded;
25
public Bound upperBound() {
29
public boolean isUpperNonstrict() {
30
return isUpperIncluded;
34
public boolean isSatisfied(BigDecimal age) {
35
if (upper instanceof InfBound)
37
int comparison = age.compareTo(new BigDecimal(upper.value()));
39
return isUpperIncluded ? comparison <= 0 : comparison < 0;
42
public static TimeInvariant parse(String invariant,
43
Map<String, Constant> constants) {
44
Pattern pattern = Pattern.compile("^(<|<=)\\s*(\\w+)$");
45
Matcher matcher = pattern.matcher(invariant);
48
String operator = matcher.group(1);
49
String boundAsString = matcher.group(2);
51
if (operator.equals("<") && boundAsString.equals("0"))
53
if (operator.equals("<=") && boundAsString.equals("inf"))
57
if (boundAsString.equals("inf"))
58
bound = Bound.Infinity;
61
int intBound = Integer.parseInt(boundAsString);
62
bound = new IntBound(intBound);
63
} catch (NumberFormatException e) {
64
if (constants.containsKey(boundAsString)) {
65
bound = new ConstantBound(constants.get(boundAsString));
67
throw new RuntimeException("A constant which was not declared was used in an invariant.");
71
return new TimeInvariant(operator.equals("<="), bound);
74
public TimeInvariant copy() {
75
return new TimeInvariant(this.isUpperIncluded, upper.copy());
79
public String toString() {
80
StringBuffer buffer = new StringBuffer();
81
buffer.append(isUpperIncluded ? "<=" : "<");
84
return buffer.toString();
87
public String toString(boolean displayConstantNames) {
88
StringBuffer buffer = new StringBuffer();
89
buffer.append(isUpperIncluded ? "<=" : "<");
91
buffer.append(displayConstantNames || upper instanceof InfBound ? upper : upper.value());
92
return buffer.toString();
97
public int hashCode() {
100
result = prime * result + (isUpperIncluded ? 1231 : 1237);
101
result = prime * result + ((upper == null) ? 0 : upper.hashCode());
106
public boolean equals(Object obj) {
111
if (!(obj instanceof TimeInvariant))
113
TimeInvariant other = (TimeInvariant) obj;
114
if (isUpperIncluded != other.isUpperIncluded)
117
if (other.upper != null)
119
} else if (!upper.equals(other.upper))