aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/logic/src/main/java/tools/refinery/logic/term/ConstantTerm.java
blob: 69c7e5f6ef76a736771849c4db10c2a17eabc261 (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
/*
 * SPDX-FileCopyrightText: 2021-2023 The Refinery Authors <https://refinery.tools/>
 *
 * SPDX-License-Identifier: EPL-2.0
 */
package tools.refinery.logic.term;

import tools.refinery.logic.equality.LiteralHashCodeHelper;
import tools.refinery.logic.InvalidQueryException;
import tools.refinery.logic.equality.LiteralEqualityHelper;
import tools.refinery.logic.substitution.Substitution;
import tools.refinery.logic.valuation.Valuation;

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

// {@link Object#equals(Object)} is implemented by {@link AbstractTerm}.
@SuppressWarnings("squid:S2160")
public final class ConstantTerm<T> extends AbstractTerm<T> {
	private final T value;

	public ConstantTerm(Class<T> type, T value) {
		super(type);
		if (value != null && !type.isInstance(value)) {
			throw new InvalidQueryException("Value %s is not an instance of %s".formatted(value, type.getName()));
		}
		this.value = value;
	}

	public T getValue() {
		return value;
	}

	@Override
	public T evaluate(Valuation valuation) {
		return getValue();
	}

	@Override
	public Term<T> substitute(Substitution substitution) {
		return this;
	}

	@Override
	public boolean equalsWithSubstitution(LiteralEqualityHelper helper, AnyTerm other) {
		if (!super.equalsWithSubstitution(helper, other)) {
			return false;
		}
		var otherConstantTerm = (ConstantTerm<?>) other;
		return Objects.equals(value, otherConstantTerm.value);
	}

	@Override
	public int hashCodeWithSubstitution(LiteralHashCodeHelper helper) {
		return Objects.hash(super.hashCodeWithSubstitution(helper), Objects.hash(value));
	}

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

	@Override
	public String toString() {
		return value.toString();
	}
}