summaryrefslogtreecommitdiff
path: root/dice-lang/src/main/java/bjc/dicelang/ast/nodes/ILiteralDiceNode.java
blob: 994a680f971b107a571c82ba968634a00f2f2437 (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
62
63
64
65
66
67
68
69
70
package bjc.dicelang.ast.nodes;

import org.apache.commons.lang3.StringUtils;

/**
 * Represents a literal of some type in the AST
 * 
 * @author ben
 *
 */
public interface ILiteralDiceNode extends IDiceASTNode {
	@Override
	default DiceASTType getType() {
		return DiceASTType.LITERAL;
	}

	@Override
	default boolean isOperator() {
		return false;
	}

	/**
	 * Get the type of literal this node represents
	 * 
	 * @return The type of literal this node represents
	 */
	DiceLiteralType getLiteralType();

	/**
	 * Optimize this node to a constant if possible
	 * 
	 * @return This node in constant form if possible
	 * @see bjc.dicelang.IDiceExpression#optimize()
	 */
	int optimize();

	/**
	 * Check if this node can be optimized to a constant
	 * 
	 * @return Whether or not this node can be optimized to a constant
	 * @see bjc.dicelang.IDiceExpression#canOptimize()
	 */
	boolean canOptimize();

	/**
	 * Check if a token represents a literal, and if so, what type
	 * 
	 * @param tok
	 *            The token to check
	 * @return The type the literal would be if it is one, or null
	 *         otherwise
	 */
	static DiceLiteralType getLiteralType(String tok) {
		if (StringUtils.countMatches(tok, 'c') == 1
				&& !tok.equalsIgnoreCase("c")) {
			return DiceLiteralType.DICE;
		} else if (StringUtils.countMatches(tok, 'd') == 1
				&& !tok.equalsIgnoreCase("d")) {
			return DiceLiteralType.DICE;
		} else {
			try {
				Integer.parseInt(tok);
				return DiceLiteralType.INTEGER;
			} catch (@SuppressWarnings("unused") NumberFormatException nfex) {
				// We don't care about details
				return null;
			}
		}
	}
}