summaryrefslogtreecommitdiff
path: root/dice-lang/src/bjc/dicelang/v1/ast/DiceASTReferenceChecker.java
blob: 5be209083c6e660d5c718dc728a62c0fe5269a18 (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
package bjc.dicelang.v1.ast;

import java.util.function.Consumer;

import bjc.dicelang.v1.ast.nodes.DiceASTType;
import bjc.dicelang.v1.ast.nodes.IDiceASTNode;
import bjc.dicelang.v1.ast.nodes.VariableDiceNode;
import bjc.utils.data.IHolder;

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