summaryrefslogtreecommitdiff
path: root/base/src/main/java/bjc/utils/parserutils/delims/DelimiterGroup.java
blob: 75f777cb64e0016764d4cc602835bb53666062ee (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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
package bjc.utils.parserutils.delims;

import java.util.Arrays;
import java.util.Deque;
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 java.util.function.BiPredicate;
import java.util.function.Function;

import bjc.data.Pair;
import bjc.data.Tree;
import bjc.data.SimplePair;
import bjc.data.SimpleTree;
import bjc.funcdata.FunctionalList;
import bjc.funcdata.ListEx;

/**
 * Represents a possible delimiter group to match.
 *
 * @author EVE
 *
 * @param <T>
 *            The type of items in the sequence.
 */
public class DelimiterGroup<T> {
	/**
	 * Represents an instance of a delimiter group.
	 *
	 * @author EVE
	 *
	 */
	public class OpenGroup {
		/*
		 * The contents of this group.
		 */
		private final Deque<Tree<T>> contents;

		/*
		 * The contents of the current subgroup.
		 */
		private ListEx<Tree<T>> currentGroup;

		/*
		 * The token that opened the group, and any opening parameters.
		 */
		private final T opener;
		private final T[] params;

		/**
		 * Create a new instance of a delimiter group.
		 *
		 * @param open
		 *              The item that opened this group.
		 *
		 * @param parms
		 *              Any parameters from the opener.
		 */
		public OpenGroup(final T open, final T[] parms) {
			opener = open;
			params = parms;

			contents = new LinkedList<>();

			currentGroup = new FunctionalList<>();
		}

		/**
		 * Add an item to this group instance.
		 *
		 * @param itm
		 *            The item to add to this group instance.
		 */
		public void addItem(final Tree<T> itm) {
			currentGroup.add(itm);
		}

		/**
		 * Mark a subgroup.
		 *
		 * @param marker
		 *               The item that indicated this subgroup.
		 *
		 * @param chars
		 *               The characteristics for building the tree.
		 */
		public void markSubgroup(final T marker, final SequenceCharacteristics<T> chars) {
			/*
			 * Add all of the contents to the subgroup.
			 */
			final Tree<T> subgroupContents = new SimpleTree<>(chars.contents);
			for (final Tree<T> itm : currentGroup) {
				subgroupContents.addChild(itm);
			}

			/*
			 * Handle subordinate sub-groups.
			 */
			while (!contents.isEmpty()) {
				final Tree<T> possibleSubordinate = contents.peek();

				/*
				 * Subordinate lower priority subgroups.
				 */
				if (possibleSubordinate.getHead().equals(chars.subgroup)) {
					final T otherMarker = possibleSubordinate.getChild(1).getHead();

					if (subgroups.get(marker) > subgroups.get(otherMarker)) {
						subgroupContents.prependChild(contents.pop());
					} else {
						break;
					}
				} else {
					subgroupContents.prependChild(contents.pop());
				}
			}

			final SimpleTree<T> subgroup
					= new SimpleTree<>(chars.subgroup, subgroupContents, new SimpleTree<>(marker));

			contents.push(subgroup);

			currentGroup = new FunctionalList<>();
		}

		/**
		 * Convert this group into a tree.
		 *
		 * @param closer
		 *               The item that closed this group.
		 *
		 * @param chars
		 *               The characteristics for building the tree.
		 *
		 * @return This group as a tree.
		 */
		public Tree<T> toTree(final T closer, final SequenceCharacteristics<T> chars) {
			/*
			 * Mark any implied subgroups.
			 */
			if (impliedSubgroups.containsKey(closer)) {
				markSubgroup(impliedSubgroups.get(closer), chars);
			}

			/* The resulting tree. */
			final Tree<T> res = new SimpleTree<>(chars.contents);

			/*
			 * Add either the contents of the current group, or subgroups if they're
			 * there.
			 */
			if (contents.isEmpty()) {
				currentGroup.forEach(res::addChild);
			} else {
				while (!contents.isEmpty()) {
					res.prependChild(contents.poll());
				}

				currentGroup.forEach(res::addChild);
			}

			return new SimpleTree<>(groupName, new SimpleTree<>(opener), res, new SimpleTree<>(closer));
		}

		@Override
		public String toString() {
			final StringBuilder builder = new StringBuilder();

			builder.append("OpenGroup [contents=");
			builder.append(contents);
			builder.append(", currentGroup=");
			builder.append(currentGroup);
			builder.append(", opener=");
			builder.append(opener);
			builder.append("]");

			return builder.toString();
		}

		/**
		 * Check if a group is excluded at the top level of this group.
		 *
		 * @param grupName
		 *                 The group to check.
		 *
		 * @return Whether or not the provided group is excluded.
		 */
		public boolean excludes(final T grupName) {
			return topLevelExclusions.contains(grupName);
		}

		/**
		 * Check if the provided delimiter would close this group.
		 *
		 * @param del
		 *            The string to check as a closing delimiter.
		 *
		 * @return Whether or not the provided delimiter closes this group.
		 */
		public boolean isClosing(final T del) {
			if (closingDelimiters.contains(del))
				return true;

			for (final BiPredicate<T, T[]> pred : predClosers) {
				if (pred.test(del, params))
					return true;
			}

			return closingDelimiters.contains(del);
		}

		/**
		 * Get the name of the group this is an instance of.
		 *
		 * @return The name of the group this is an instance of.
		 */
		public T getName() {
			return groupName;
		}

		/**
		 * Get the groups that aren't allowed at all in this group.
		 *
		 * @return The groups that aren't allowed at all in this group.
		 */
		public Set<T> getNestingExclusions() {
			return groupExclusions;
		}

		/**
		 * Get the groups that are allowed to open anywhere inside this group.
		 *
		 * @return The groups allowed to open anywhere inside this group.
		 */
		public Map<T, T> getNestingOpeners() {
			return nestedOpenDelimiters;
		}

		/**
		 * Checks if a given token marks a subgroup.
		 *
		 * @param tok
		 *            The token to check.
		 *
		 * @return Whether or not the token marks a subgroup.
		 */
		public boolean marksSubgroup(final T tok) {
			return subgroups.containsKey(tok);
		}

		/**
		 * Checks if a given token opens a group.
		 *
		 * @param marker
		 *               The token to check.
		 *
		 * @return The name of the group T opens, or null if it doesn't open one.
		 */
		public Pair<T, T[]> doesOpen(final T marker) {
			if (openDelimiters.containsKey(marker))
				return new SimplePair<>(openDelimiters.get(marker), null);

			for (final Function<T, Pair<T, T[]>> pred : predOpeners) {
				final Pair<T, T[]> par = pred.apply(marker);

				if (par.getLeft() != null)
					return par;
			}

			return new SimplePair<>(null, null);
		}

		/**
		 * Check if this group starts a new nesting scope.
		 *
		 * @return Whether this group starts a new nesting scope.
		 */
		public boolean isForgetful() {
			return forgetful;
		}
	}

	/**
	 * The name of this delimiter group.
	 */
	public final T groupName;

	/* The delimiters that open groups at the top level of this group. */
	private final Map<T, T> openDelimiters;

	/* The delimiters that open groups inside of this group. */
	private final Map<T, T> nestedOpenDelimiters;

	/* The delimiters that close this group. */
	private final Set<T> closingDelimiters;

	/* The groups that can't occur in the top level of this group. */
	private final Set<T> topLevelExclusions;

	/* The groups that can't occur anywhere inside this group. */
	private final Set<T> groupExclusions;

	/*
	 * Mapping from sub-group delimiters, to any sub-groups enclosed in them.
	 */
	private final Map<T, Integer> subgroups;

	/* Subgroups implied by a particular closing delimiter */
	private final Map<T, T> impliedSubgroups;

	/* Allows more complex openings */
	private final List<Function<T, Pair<T, T[]>>> predOpeners;

	/* Allow more complex closings */
	private final List<BiPredicate<T, T[]>> predClosers;

	/* Whether or not this group starts a new nesting set. */
	private boolean forgetful;

	/**
	 * Create a new empty delimiter group.
	 *
	 * @param name
	 *             The name of the delimiter group
	 */
	public DelimiterGroup(final T name) {
		if (name == null)
			throw new NullPointerException("Group name must not be null");

		groupName = name;

		openDelimiters = new HashMap<>();
		nestedOpenDelimiters = new HashMap<>();

		closingDelimiters = new HashSet<>();

		topLevelExclusions = new HashSet<>();
		groupExclusions = new HashSet<>();

		subgroups = new HashMap<>();
		impliedSubgroups = new HashMap<>();

		predOpeners = new LinkedList<>();
		predClosers = new LinkedList<>();
	}

	/**
	 * Adds one or more delimiters that close this group.
	 *
	 * @param closers
	 *                Delimiters that close this group.
	 */
	@SafeVarargs
	public final void addClosing(final T... closers) {
		final List<T> closerList = Arrays.asList(closers);

		for (final T closer : closerList) {
			if (closer == null) {
				throw new NullPointerException("Closing delimiter must not be null");
			} else if (closer.equals("")) {
				/*
				 * We can do this because equals works on arbitrary objects, not just
				 * those of the same type.
				 */
				throw new IllegalArgumentException(
						"Empty string is not a valid exclusion");
			} else {
				closingDelimiters.add(closer);
			}
		}
	}

	/**
	 * Adds one or more groups that cannot occur in the top level of this group.
	 *
	 * @param exclusions
	 *                   The groups forbidden in the top level of this group.
	 */
	@SafeVarargs
	public final void addTopLevelForbid(final T... exclusions) {
		for (final T exclusion : exclusions) {
			if (exclusion == null) {
				throw new NullPointerException("Exclusion must not be null");
			} else if (exclusion.equals("")) {
				/*
				 * We can do this because equals works on arbitrary objects, not just
				 * those of the same type.
				 */
				throw new IllegalArgumentException(
						"Empty string is not a valid exclusion");
			} else {
				topLevelExclusions.add(exclusion);
			}
		}
	}

	/**
	 * Adds one or more groups that cannot occur at all in this group.
	 *
	 * @param exclusions
	 *                   The groups forbidden inside this group.
	 */
	@SafeVarargs
	public final void addGroupForbid(final T... exclusions) {
		for (final T exclusion : exclusions) {
			if (exclusion == null) {
				throw new NullPointerException("Exclusion must not be null");
			} else if (exclusion.equals("")) {
				/*
				 * We can do this because equals works on arbitrary objects, not just
				 * those of the same type.
				 */
				throw new IllegalArgumentException(
						"Empty string is not a valid exclusion");
			} else {
				groupExclusions.add(exclusion);
			}
		}
	}

	/**
	 * Adds sub-group markers to this group.
	 *
	 * @param subgroup
	 *                 The token to mark a sub-group.
	 *
	 * @param priority
	 *                 The priority of this sub-group.
	 */
	public void addSubgroup(final T subgroup, final int priority) {
		if (subgroup == null)
			throw new NullPointerException("Subgroup marker must not be null");

		subgroups.put(subgroup, priority);
	}

	/**
	 * Adds a marker that opens a group at the top level of this group.
	 *
	 * @param opener
	 *               The marker that opens the group.
	 *
	 * @param group
	 *               The group opened by the marker.
	 */
	public void addOpener(final T opener, final T group) {
		if (opener == null)
			throw new NullPointerException("Opener must not be null");
		else if (group == null)
			throw new NullPointerException("Group to open must not be null");

		openDelimiters.put(opener, group);
	}

	/**
	 * Adds a marker that opens a group inside of this group.
	 *
	 * @param opener
	 *               The marker that opens the group.
	 *
	 * @param group
	 *               The group opened by the marker.
	 */
	public void addNestedOpener(final T opener, final T group) {
		if (opener == null) {
			throw new NullPointerException("Opener must not be null");
		} else if (group == null) {
			throw new NullPointerException("Group to open must not be null");
		}

		nestedOpenDelimiters.put(opener, group);
	}

	/**
	 * Mark a closing delimiter as implying a subgroup.
	 *
	 * @param closer
	 *                 The closing delimiter.
	 *
	 * @param subgroup
	 *                 The subgroup to imply.
	 */
	public void implySubgroup(final T closer, final T subgroup) {
		if (closer == null) {
			throw new NullPointerException("Closer must not be null");
		} else if (subgroup == null) {
			throw new NullPointerException("Subgroup must not be null");
		} else if (!closingDelimiters.contains(closer)) {
			throw new IllegalArgumentException(
					String.format("No closing delimiter '%s' defined", closer));
		} else if (!subgroups.containsKey(subgroup)) {
			throw new IllegalArgumentException(
					String.format("No subgroup '%s' defined", subgroup));
		}

		impliedSubgroups.put(closer, subgroup);
	}

	@Override
	public String toString() {
		final StringBuilder builder = new StringBuilder();

		builder.append("(");

		builder.append("groupName=[");
		builder.append(groupName);
		builder.append("], ");

		builder.append("closingDelimiters=[");
		for (final T closer : closingDelimiters) {
			builder.append(closer + ",");
		}
		builder.deleteCharAt(builder.length() - 1);
		builder.append("]");

		if (topLevelExclusions != null && !topLevelExclusions.isEmpty()) {
			builder.append(", ");
			builder.append("topLevelExclusions=[");
			for (final T exclusion : topLevelExclusions) {
				builder.append(exclusion + ",");
			}
			builder.deleteCharAt(builder.length() - 1);
			builder.append("]");
		}

		if (groupExclusions != null && !groupExclusions.isEmpty()) {
			builder.append(", ");
			builder.append("groupExclusions=[");
			for (final T exclusion : groupExclusions) {
				builder.append(exclusion + ",");
			}
			builder.deleteCharAt(builder.length() - 1);
			builder.append("]");
		}

		builder.append(" )");

		return builder.toString();
	}

	/**
	 * Open an instance of this group.
	 *
	 * @param opener
	 *               The item that opened this group.
	 *
	 * @param parms
	 *               The parameters that opened this group
	 *
	 * @return An opened instance of this group.
	 */
	public OpenGroup open(final T opener, final T[] parms) {
		return new OpenGroup(opener, parms);
	}

	/**
	 * Adds a predicated opener to the top level of this group.
	 *
	 * @param pred
	 *             The predicate that defines the opener and its parameters.
	 */
	public void addPredOpener(final Function<T, Pair<T, T[]>> pred) {
		predOpeners.add(pred);
	}

	/**
	 * Adds a predicated closer to the top level of this group.
	 *
	 * @param pred
	 *             The predicate that defines the closer.
	 */
	public void addPredCloser(final BiPredicate<T, T[]> pred) {
		predClosers.add(pred);
	}

	/**
	 * Set whether or not this group starts a new nesting set.
	 *
	 * @param forgetful
	 *                  Whether this group starts a new nesting set.
	 */
	public void setForgetful(final boolean forgetful) {
		this.forgetful = forgetful;
	}
}