summaryrefslogtreecommitdiff
path: root/dice-lang/src/main/java/bjc/dicelang/ast/DiceASTReferenceChecker.java
blob: a74d61e25c1fc72de3109915c67d58a1976452f1 (plain)
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
package bjc.dicelang.ast;

import java.util.function.Consumer;

import bjc.utils.data.GenHolder;

/**
 * Check if the specified node references a particular variable
 * 
 * @author ben
 *
 */
public final class DiceASTReferenceChecker
		implements Consumer<IDiceASTNode> {
	/**
	 * This is true if the specified node references the set variable
	 */
	private GenHolder<Boolean>	referencesVariable;

	private String				varName;

	/**
	 * Create a new reference checker
	 * 
	 * @param referencesVar
	 *            The holder of whether the variable is referenced or not
	 * @param varName
	 *            The variable to check for references in
	 */
	public DiceASTReferenceChecker(GenHolder<Boolean> referencesVar,
			String varName) {
		this.referencesVariable = referencesVar;
		this.varName = varName;
	}

	@Override
	public void accept(IDiceASTNode astNode) {
		if (!referencesVariable.unwrap(bool -> bool)) {
			if (isDirectReference(astNode)) {
				referencesVariable.transform((bool) -> false);
			}
		}
	}

	/**
	 * Check if a given AST node directly references the specified variable
	 * 
	 * @param astNode
	 *            The node to check
	 * @return Whether or not the node directly the variable
	 */
	private boolean isDirectReference(IDiceASTNode astNode) {
		if (astNode.getType() == DiceASTType.VARIABLE) {
			VariableDiceNode node = (VariableDiceNode) astNode;

			return node.getVariable().equals(varName);
		} else {
			return false;
		}
	}
}