summaryrefslogtreecommitdiff
path: root/src/main/java/bjc/rgens/parser/Rule.java
blob: 15e9b5fc9749a41886dfe06f52c5d56631ce6a5a (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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
package bjc.rgens.parser;

import static bjc.rgens.parser.RGrammarLogging.fine;
import static bjc.utils.data.IPair.pair;

import bjc.utils.data.IPair;
import bjc.utils.data.ITree;
import bjc.utils.data.Tree;
import bjc.utils.funcdata.FunctionalList;
import bjc.utils.funcdata.IList;
import bjc.utils.gen.WeightedRandom;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import bjc.utils.data.IPair;
import bjc.utils.funcdata.IList;
import bjc.utils.gen.WeightedRandom;

/**
 * A rule in a randomized grammar.
 *
 * @author EVE
 */
public class Rule {
	public RGrammar belongsTo;

	/** The name of this grammar rule. */
	public String name;

	/* The cases for this rule. */
	private WeightedRandom<RuleCase> cases;

	/*
	 * @NOTE
	 *
	 * Perhaps this should be split into subclasses along prob type? I'm not
	 * sure as to whether or not that would be a useful thing to do.
	 */
	public static enum ProbType {
		NORMAL,
		DESCENDING,
		BINOMIAL
	}
	
	public ProbType prob;

	// Probability vars
	/* Descent vars */
	public int descentFactor;
	/* Binomial vars */
	public int target;
	public int bound;
	public int trials;

	private List<String> rejectionPreds;
	private List<IPair<String, String>> findReplaces;

	// @TODO This default should be configurable in some way
	public int recurLimit = 5;
	private int currentRecur;

	private final static Random BASE = new Random();

	private int caseCount = 0;

	@SuppressWarnings("unused")
	private int serial;
	private static int nextSerial = 0;

	/**
	 * 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) {
		serial = ++nextSerial;

		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");
		}

		name = ruleName;

		cases = new WeightedRandom<>();

		prob = ProbType.NORMAL;

		rejectionPreds = new ArrayList<>();
		findReplaces = new ArrayList<>();
	}

	/**
	 * Adds a case to the rule.
	 *
	 * @param cse
	 * 	The case to add.
	 */
	public void addCase(RuleCase cse) {
		addCase(cse, 1);
	}

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

		cse.belongsTo = this;
		cse.debugName = String.format("%s-%d", name, ++caseCount);

		cases.addProbability(weight, cse);
	}

	public void addRejection(String reject) {
		addRejection(reject, new Tree<>());
	}

	public void addRejection(String reject, ITree<String> errs) {
		try {
			Pattern.compile(reject);
		} catch (PatternSyntaxException psex) {
			String msg = String.format("ERROR: '%s' is not a valid regex for rejection (%s)", reject, psex.getMessage());
		}

		rejectionPreds.add(reject);
	}

	public void addFindReplace(String find, String replace) {
		addFindReplace(find, replace, new Tree<>());
	}

	public void addFindReplace(String find, String replace, ITree<String> errs) {
		try {
			Pattern.compile(find);
		} catch (PatternSyntaxException psex) {
			String msg = String.format("ERROR: '%s' is not a valid regex for finding (%s)", find, psex.getMessage());

			errs.addChild(msg);

			return;
		}

		findReplaces.add(pair(find, replace));
	}

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

	/**
	 * Get a random case from this rule.
	 *
	 * @param rnd
	 * 	The random number generator to use.
	 *
	 * @return
	 * 	A random case from this rule.
	 */
	public RuleCase getCase(Random rnd) {
		switch(prob) {
		case DESCENDING:
			return cases.getDescent(descentFactor, rnd);
		case BINOMIAL:
			return cases.getBinomial(target, bound, trials, rnd);
		case NORMAL:
			return cases.generateValue(rnd);
		default:
			return cases.generateValue(rnd);
		}
	}

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

	/**
	 * Replace the current list of cases with a new one.
	 *
	 * @param cases
	 * 	The new list of cases.
	 */
	public void replaceCases(IList<IPair<Integer, RuleCase>> cases) {
		this.cases = new WeightedRandom<>();

		for(IPair<Integer, RuleCase> cse : cases) {
			RuleCase cs = cse.getRight();
			cs.belongsTo = this;
			cs.debugName = String.format("%s-%d", name, ++caseCount);

			this.cases.addProbability(cse.getLeft(), cs);
		}
	}

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

		int result = 1;
		result = prime * result + ((cases == null) ? 0 : cases.hashCode());
		result = prime * result + ((name == null) ? 0 : name.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 (cases == null) {
			if (other.cases != null) return false;
		} else if (!cases.equals(other.cases)) return false;

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

		return true;
	}

	@Override
	public String toString() {
		return String.format("Rule '%s' with %d cases", name, cases.getValues().getSize());
	}

	public boolean doRecur() {
		if(currentRecur > recurLimit) return false;

		currentRecur += 1;

		return true;
	}

	public void endRecur() {
		if(currentRecur > 0) currentRecur -= 1;
		else throw new IllegalStateException("endRecur without matching doRecur");
	}

	public Rule exhaust() {
		Rule rl = new Rule(name);

		rl.belongsTo = belongsTo;

		rl.cases = cases.exhaustible();

		rl.prob = prob;

		rl.descentFactor = descentFactor;

		rl.target = target;
		rl.bound  = bound;
		rl.trials = trials;

		rl.recurLimit = recurLimit;
		/* @NOTE 
		 *
		 * Is this the right thing to do?
		 *
		 * At least for now it is. I can't think of any intentional
		 * situations where this would cause issues, but it'll be kept
		 * in mind -- 8/14/18
		 */
		rl.currentRecur = 0;

		return rl;
	}

	public void generate(GenerationState state) {
		state.swapGrammar(belongsTo);

		boolean rejected;

		do {
			rejected = false;

			if(doRecur()) {
				RuleCase cse = getCase(state.rnd);

				fine("Generating %s (from %s)", cse, belongsTo.name);

				belongsTo.generateCase(cse, state);

				endRecur();
			}

			// Don't rebuild the builder a bunch
			String conts = state.getContents();
			if(name.contains("+")) {
				conts = conts.replaceAll("\\s+", "");
			}

			for(IPair<String, String> findRep : findReplaces) {
				conts = conts.replaceAll(findRep.getLeft(), findRep.getRight());
			}
			state.setContents(conts);

			for(String pat : rejectionPreds) {
				if(!conts.matches(pat)) {
					fine("Rejected %s by %s (from %s)", conts, pat, belongsTo.name);

					rejected = true;
					state.clearContents();

					break;
				}
			}
		} while (rejected);
	}
}