summaryrefslogtreecommitdiff
path: root/dice-lang/src/main/java/bjc/dicelang/ast/DiceASTReferenceChecker.java
blob: 34414c57540ebeaf87101fabe7d4e4b0bce2dd68 (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.IHolder;

import bjc.dicelang.ast.nodes.DiceASTType;
import bjc.dicelang.ast.nodes.IDiceASTNode;
import bjc.dicelang.ast.nodes.VariableDiceNode;

/**
 * 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 IHolder<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(IHolder<Boolean> referencesVar,
			String varName) {
		this.referencesVariable = referencesVar;
		this.varName = varName;
	}

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

	/**
	 * 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);
		}

		return false;
	}
}