aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/store-query/src/main/java/tools/refinery/store/query/term/UnaryTerm.java
blob: 4083111a05e5701ca4791ba4f437ea4d4c26adc5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package tools.refinery.store.query.term;

import tools.refinery.store.query.equality.LiteralEqualityHelper;
import tools.refinery.store.query.substitution.Substitution;
import tools.refinery.store.query.valuation.Valuation;

import java.util.Objects;
import java.util.Set;

public abstract class UnaryTerm<R, T> implements Term<R> {
	private final Term<T> body;

	protected UnaryTerm(Term<T> body) {
		if (!body.getType().equals(getBodyType())) {
			throw new IllegalArgumentException("Expected body %s to be of type %s, got %s instead".formatted(body,
					getBodyType().getName(), body.getType().getName()));
		}
		this.body = body;
	}

	public abstract Class<T> getBodyType();

	public Term<T> getBody() {
		return body;
	}

	@Override
	public R evaluate(Valuation valuation) {
		var bodyValue = body.evaluate(valuation);
		return bodyValue == null ? null : doEvaluate(bodyValue);
	}

	protected abstract R doEvaluate(T bodyValue);

	@Override
	public boolean equalsWithSubstitution(LiteralEqualityHelper helper, AnyTerm other) {
		if (getClass() != other.getClass()) {
			return false;
		}
		var otherUnaryTerm = (UnaryTerm<?, ?>) other;
		return body.equalsWithSubstitution(helper, otherUnaryTerm.body);
	}

	@Override
	public Term<R> substitute(Substitution substitution) {
		return doSubstitute(substitution, body.substitute(substitution));
	}

	protected abstract Term<R> doSubstitute(Substitution substitution, Term<T> substitutedBody);

	@Override
	public Set<AnyDataVariable> getInputVariables() {
		return body.getInputVariables();
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (o == null || getClass() != o.getClass()) return false;
		UnaryTerm<?, ?> unaryTerm = (UnaryTerm<?, ?>) o;
		return body.equals(unaryTerm.body);
	}

	@Override
	public int hashCode() {
		return Objects.hash(getClass(), body);
	}
}