summaryrefslogtreecommitdiff
path: root/src/main/java/bjc/rgens/parser/RGrammarBuilder.java
blob: 45569a50377344b038b55f70e84ea35d884d4467 (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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
package bjc.rgens.parser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import bjc.rgens.parser.elements.CaseElement;
import bjc.utils.data.IPair;
import bjc.utils.data.ITree;
import bjc.utils.data.Pair;
import bjc.utils.data.Tree;

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

import bjc.utils.funcutils.ListUtils;
import bjc.utils.funcutils.SetUtils;

/**
 * Construct randomized grammars piece by piece.
 *
 * @author EVE
 */
public class RGrammarBuilder {
	/* The rules being built. */
	private Map<String, Rule> rules;
	/* The current set of exported rules. */
	private Set<String> exportedRules;
	/* The current initial rule. */
	private String initialRule;
	/* The current grammar name. */
	public String name;

	/* Autovivify variables */
	private Map<String, CaseElement> autoVars;
	private Map<String, CaseElement> autoRlVars;

	/** Create a new randomized grammar builder. */
	public RGrammarBuilder() {
		rules = new HashMap<>();

		exportedRules = new HashSet<>();

		autoVars = new HashMap<>();
		autoRlVars = new HashMap<>();
	}

	/**
	 * Get or create a rule by the given name.
	 *
	 * @param rName
	 * 	The name of the rule.
	 *
	 * @return
	 * 	The rule by that name, or a new one if none existed.
	 */
	public Rule getOrCreateRule(String rName) {
		return getOrCreateRule(rName, new Tree<>());
	}

	public Rule getOrCreateRule(String rName, ITree<String> errs) {
		if(rName == null) {
			errs.addChild("ERROR: Rule name must not be null");

			return null;
		} else if(rName.equals("")) {
			errs.addChild("ERROR: The empty string is not a valid rule name");

			return null;
		}

		if(rules.containsKey(rName)) {
			return rules.get(rName);
		} else {
			Rule ret = new Rule(rName);

			rules.put(rName, ret);

			return ret;
		}
	}

	/**
	 * Convert this builder into a grammar.
	 *
	 * @return 
	 * 	The grammar built by this builder
	 */
	public RGrammar toRGrammar() {
		RGrammar grammar = new RGrammar(rules);
		grammar.name = name;

		if(initialRule != null) {
			if(!rules.containsKey(initialRule)) {
				throw new GrammarException(String.format("Rule '%s' doesn't exist", initialRule));
			}
		}

		grammar.setInitialRule(initialRule);

		for(String export : exportedRules) {
			if(!rules.containsKey(export)) {
				throw new GrammarException(String.format("Rule '%s' doesn't exist", export));
			}
		}

		grammar.setExportedRules(exportedRules);

		grammar.setAutoVars(autoVars, autoRlVars);

		return grammar;
	}

	/**
	 * Set the initial rule of the grammar.
	 *
	 * @param init
	 * 	The initial rule of the grammar.
	 *
	 * @throws IllegalArgumentException
	 * 	If the rule is either not valid or not defined in the grammar.
	 */
	public void setInitialRule(String init) {
	}

	public void setInitialRule(String init, ITree<String> errs) {
		if (init == null) {
			errs.addChild("init must not be null");

			return;
		} else if (init.equals("")) {
			errs.addChild("The empty string is not a valid rule name");

			return;
		}

		initialRule = init;
	}

	/**
	 * Add an exported rule to this grammar.
	 *
	 * @param export
	 * 	The name of the rule to export.
	 *
	 * @throws IllegalArgumentException
	 * 	If the rule is either not valid or not defined in the grammar.
	 */
	public void addExport(String export) {
		addExport(export, new Tree<>());
	}

	public void addExport(String export, ITree<String> errs) {
		if (export == null) {
			errs.addChild("ERROR: Export name must not be null");

			return;
		} else if (export.equals("")) {
			errs.addChild("ERROR: The empty string is not a valid rule name");

			return;
		}

		exportedRules.add(export);
	}

	/**
	 * Suffix a given case element to every case of a specific rule.
	 *
	 * @param ruleName
	 * 	The rule to suffix.
	 *
	 * @param suffixes
	 * 	The suffixes to add.
	 *
	 * @throws IllegalArgumentException
	 * 	If the rule name is either invalid or not defined by this
	 * 	grammar, or if the suffix is invalid.
	 */
	public void suffixWith(String ruleName, List<CaseElement> suffixes) {
		affixWith(ruleName, suffixes, AffixType.SUFFIX, new Tree<>());
	}


	/**
	 * Prefix a given case element to every case of a specific rule.
	 *
	 * @param ruleName
	 * 	The rule to prefix.
	 *
	 * @param prefixes
	 * 	The prefixes to add.
	 *
	 * @throws IllegalArgumentException
	 * 	If the rule name is either invalid or not defined by this
	 * 	grammar, or if the prefix is invalid.
	 */
	public void prefixWith(String ruleName, List<CaseElement> prefixes) {
		affixWith(ruleName, prefixes, AffixType.PREFIX, new Tree<>());
	}

	/**
	 * Prefix and suffix a given case element to every case of a specific rule.
	 *
	 * @param ruleName
	 * 	The rule to prefix and suffix.
	 *
	 * @param prefixes
	 * 	The prefixes/suffixes to add.
	 *
	 * @throws IllegalArgumentException
	 * 	If the rule name is either invalid or not defined by this
	 * 	grammar, or if the prefix/suffix is invalid.
	 */
	public void circumfixWith(String ruleName, List<CaseElement> prefixes) {
		affixWith(ruleName, prefixes, AffixType.CIRCUMFIX, new Tree<>());
	}

	public static enum AffixType {
		CIRCUMFIX,
		SUFFIX,
		PREFIX;

		public boolean isSuffix() {
			return this != PREFIX;
		}

		public boolean isPrefix() {
			return this != SUFFIX;
		}
	}

	public void affixWith(String ruleName, List<CaseElement> affixes, AffixType type) {
		affixWith(ruleName, affixes, type, new Tree<>());
	}

	public void affixWith(String ruleName, List<CaseElement> affixes, AffixType type, ITree<String> errs) {
		if (ruleName == null) {
			errs.addChild("ERROR: Rule name must not be null");

			return;
		} else if (ruleName.equals("")) {
			errs.addChild("ERROR: The empty string is not a valid rule name");

			return;
		} else if(!rules.containsKey(ruleName)) {
			String msg = String.format("ERROR: Rule '%s' is not a valid rule name");

			errs.addChild(msg);

			return;
		}

		Set<CaseElement> elements = new HashSet<>(affixes);
		
		List<List<CaseElement>> affixLists = powerList(elements);

		FunctionalList<IPair<Integer, RuleCase>> newCases = new FunctionalList<>();
		IList<IPair<Integer, RuleCase>> caseList = rules.get(ruleName).getCases();

		for (IPair<Integer, RuleCase> ruleCase : caseList) {
			RuleCase cas = ruleCase.getRight();

			for(List<CaseElement> affixList : affixLists) {
				List<CaseElement> newCase = new ArrayList<>();

				if(type.isPrefix()) {
					for(CaseElement element : affixList) {
						newCase.add(element);
					}
				}

				for(CaseElement elm : cas.elementList) {
					newCase.add(elm);
				}
				
				if(type.isSuffix()) {
					for(CaseElement element : affixList) {
						newCase.add(element);
					}
				}


				newCases.add(new Pair<>(ruleCase.getLeft(), cas.withElements(newCase)));
			}
		}


		for (IPair<Integer, RuleCase> newCase : newCases) {
			rules.get(ruleName).addCase(newCase.getRight(), newCase.getLeft());
		}
	}

	public void despaceRule(String ruleName) {
		despaceRule(ruleName, new Tree<>(), false);
	}

	public void despaceRule(String ruleName, ITree<String> errs, boolean doTrace) {
		if (ruleName == null) {
			 errs.addChild("ERROR: Rule name must not be null");

			 return;
		} else if (ruleName.equals("")) {
			errs.addChild("ERROR: The empty string is not a valid rule name");

			return;
		} else if (!rules.containsKey(ruleName)) {
			String msg = String.format("ERROR: The rule '%s' doesn't exist", ruleName);

			errs.addChild(msg);

			return;
		}

		IList<IPair<Integer, RuleCase>> caseList = rules.get(ruleName).getCases();

		IList<IPair<Integer, RuleCase>> newCaseList = new FunctionalList<>();

		for(IPair<Integer, RuleCase> cse : caseList) {
			newCaseList.add(new Pair<>(cse.getLeft(), new FlatRuleCase(cse.getRight().elementList)));
		}

		if (doTrace) {
			String msg = String.format("TRACE: Despacing %d cases of rule %s", caseList.getSize(), ruleName);

			errs.addChild(msg);
		}

		rules.get(ruleName).replaceCases(newCaseList);
	}

	public void setWeight(String ruleName) {
		setWeight(ruleName, new Tree<>());
	}

	public void setWeight(String ruleName, ITree<String> errs) {
		if (ruleName == null) {
			errs.addChild("ERROR: Rule name must not be null");

			return;
		} else if (ruleName.equals("")) {
			errs.addChild("ERROR: The empty string is not a valid rule name");

			return;
		} else if (!rules.containsKey(ruleName)) {
			String msg = String.format("ERROR: The rule '%s' doesn't exist", ruleName);

			errs.addChild(msg);

			return;
		}

		rules.get(ruleName).prob = Rule.ProbType.NORMAL;
	}

	public void setRuleRecur(String ruleName, int recurLimit) {
		setRuleRecur(ruleName, recurLimit, new Tree<>());
	}

	public void setRuleRecur(String ruleName, int recurLimit, ITree<String> errs) {
		if (ruleName == null) {
			errs.addChild("ERROR: Rule name must not be null");

			return;
		} else if (ruleName.equals("")) {
			errs.addChild("ERROR: The empty string is not a valid rule name");

			return;
		} else if (!rules.containsKey(ruleName)) {
			String msg = String.format("ERROR: The rule '%s' doesn't exist", ruleName);

			errs.addChild(msg);

			return;
		}

		rules.get(ruleName).recurLimit = recurLimit;
	}

	public void setDescent(String ruleName, int descentFactor) {
		setDescent(ruleName, descentFactor, new Tree<>());
	}

	public void setDescent(String ruleName, int descentFactor, ITree<String> errs) {
		if (ruleName == null) {
			errs.addChild("ERROR: Rule name must not be null");

			return;
		} else if (ruleName.equals("")) {
			errs.addChild("ERROR: The empty string is not a valid rule name");

			return;
		} else if (!rules.containsKey(ruleName)) {
			String msg = String.format("ERROR: The rule '%s' doesn't exist", ruleName);

			errs.addChild(msg);

			return;
		}

		Rule rl = rules.get(ruleName);

		rl.prob          = Rule.ProbType.DESCENDING;
		rl.descentFactor = descentFactor;
	}

	public void setBinomial(String ruleName, int target, int bound, int trials) {
		setBinomial(ruleName, target, bound, trials, new Tree<>());
	}

	public void setBinomial(String ruleName, int target, int bound, int trials, ITree<String> errs) {
		if (ruleName == null) {
			errs.addChild("ERROR: Rule name must not be null");

			return;
		} else if (ruleName.equals("")) {
			errs.addChild("ERROR: The empty string is not a valid rule name");

			return;
		} else if (!rules.containsKey(ruleName)) {
			String msg = String.format("ERROR: The rule '%s' doesn't exist", ruleName);
			errs.addChild(msg);

			return;
		}

		Rule rl = rules.get(ruleName);

		rl.prob = Rule.ProbType.BINOMIAL;

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

	public void addAutoVar(String name, CaseElement elm) {
		autoVars.put(name, elm);
	}

	public void addAutoRlVar(String name, CaseElement elm) {
		autoRlVars.put(name, elm);
	}

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

	public void rejectRule(String rule, String reject, ITree<String> errs) {
		if (rule == null) {
			errs.addChild("ERROR: Rule must not be null");

			return;
		} else if(reject == null) {
			errs.addChild("ERROR: Reject must not be null");	

			return;
		} else if (rule.equals("")) {
			errs.addChild("ERROR: The empty string is not a valid rule name");

			return;
		} else if(!rules.containsKey(rule)) {
			String msg = String.format("ERROR: The rule '%s' doesn't exist", rule);

			errs.addChild(msg);

			return;
		}

		Rule rl = rules.get(rule);

		rl.addRejection(reject, errs);
	}

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

	public void findReplaceRule(String rule, String find, String replace, ITree<String> errs) {
		if (rule == null) {
			errs.addChild("ERROR: Rule must not be null");

			return;
		} else if(find == null) {
			errs.addChild("ERROR: Find must not be null");	

			return;
		} else if(replace == null) {
			errs.addChild("ERROR: Replace must not be null");	

			return;
		} else if (rule.equals("")) {
			errs.addChild("ERROR: The empty string is not a valid rule name");

			return;
		} else if(!rules.containsKey(rule)) {
			String msg = String.format("ERROR: The rule '%s' doesn't exist", rule);

			errs.addChild(msg);

			return;
		}

		Rule rl = rules.get(rule);

		rl.addFindReplace(find, replace, errs);
	}

	/*
	 * @NOTE
	 *
	 * This should be moved into its own class somewhere, as it is general
	 * enough.
	 */
	private static <T> List<List<T>> powerList(Set<T> elements) {
		/*
		 * Fast-case the most common usage
		 */
		if(elements.size() == 1) {
			List<List<T>> ret = new LinkedList<>();

			List<T> curr = new ArrayList<>(elements.size());
			for(T elem : elements) {
				curr.add(elem);
			}

			ret.add(curr);

			return ret;
		}

		Set<Set<T>> powerSet = SetUtils.powerSet(elements);

		List<List<T>> list = new LinkedList<>();

		for(Set<T> set : powerSet) {
			/*
			 * Skip empty sets
			 */
			if(set.size() == 0) continue;

			List<T> stor = new ArrayList<>(set.size());

			for(T elm : set) {
				stor.add(elm);
			}

			for(List<T> permute : ListUtils.permuteList(stor)) {
				//System.err.printf("\t\tTRACE: generated permute ");
				for(T elm : permute) {
					System.err.printf("%s ", elm);
				}
				System.err.println();

				list.add(permute);
			}
		}

		return list;
	}
}