summaryrefslogtreecommitdiff
path: root/RGens/src/main/java/bjc/rgens/newparser/Rule.java
blob: a65f1ceab9415f58ad04960db6cc006fccceeacb (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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package bjc.rgens.newparser;

import bjc.utils.funcdata.FunctionalList;
import bjc.utils.funcdata.IList;

/**
 * A rule in a randomized grammar.
 * 
 * @author EVE
 *
 */
public class Rule {
	/**
	 * The name of this grammar rule.
	 */
	public final String ruleName;

	private IList<RuleCase> ruleCases;

	/**
	 * Create a new grammar rule.
	 * 
	 * @param ruleName
	 *                The name of the grammar rule.
	 * 
	 * @throws IllegalArgumentException
	 *                 If the rule name is invalid.
	 */
	public Rule(String ruleName) {
		if(ruleName == null) {
			throw new NullPointerException("Rule name must not be null");
		} else if(ruleName.equals("")) {
			throw new IllegalArgumentException("The empty string is not a valid rule name");
		}

		this.ruleName = ruleName;

		ruleCases = new FunctionalList<>();
	}

	/**
	 * Adds a case to the rule.
	 * 
	 * @param cse
	 *                The case to add.
	 */
	public void addCase(RuleCase cse) {
		if(cse == null) {
			throw new NullPointerException("Case must not be null");
		}

		ruleCases.add(cse);
	}

	/**
	 * Get a random case from this rule.
	 * 
	 * @return A random case from this rule.
	 */
	public RuleCase getCase() {
		return ruleCases.randItem();
	}

	/**
	 * Get all the cases of this rule.
	 * 
	 * @return All the cases in this rule.
	 */
	public IList<RuleCase> getCases() {
		return ruleCases;
	}

	@Override
	public int hashCode() {
		final int prime = 31;

		int result = 1;
		result = prime * result + ((ruleCases == null) ? 0 : ruleCases.hashCode());
		result = prime * result + ((ruleName == null) ? 0 : ruleName.hashCode());

		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if(this == obj) return true;
		if(obj == null) return false;
		if(!(obj instanceof Rule)) return false;

		Rule other = (Rule) obj;

		if(ruleCases == null) {
			if(other.ruleCases != null) return false;
		} else if(!ruleCases.equals(other.ruleCases)) return false;

		if(ruleName == null) {
			if(other.ruleName != null) return false;
		} else if(!ruleName.equals(other.ruleName)) return false;

		return true;
	}

	@Override
	public String toString() {
		return String.format("Rule [ruleName='%s', ruleCases=%s]", ruleName, ruleCases);
	}
}