summaryrefslogtreecommitdiff
path: root/BJC-Utils2/src/main/java/bjc/utils/parserutils/SequenceDelimiter.java
blob: 96a6c659c25b3cff2c54f806467726f7c1b5c967 (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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
package bjc.utils.parserutils;

import bjc.utils.data.ITree;
import bjc.utils.data.Tree;
import bjc.utils.esodata.PushdownMap;
import bjc.utils.esodata.SimpleStack;
import bjc.utils.esodata.Stack;
import bjc.utils.funcdata.IMap;
import bjc.utils.funcutils.StringUtils;

import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Convert linear sequences into trees that represent group structure.
 * 
 * @author EVE
 *
 * @param <T>
 *                The type of items in the sequence.
 */
public class SequenceDelimiter<T> {
	/**
	 * Represents a possible delimiter group to match.
	 * 
	 * @author EVE
	 *
	 * @param <T2>
	 *                The type of items in the sequence.
	 */
	public static class DelimiterGroup<T2> {
		/**
		 * The name of this delimiter group.
		 */
		public final T2 groupName;

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

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

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

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

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

			groupName = name;

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

		/**
		 * 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(T2 del) {
			return closingDelimiters.contains(del);
		}

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

			for(T2 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(T2... exclusions) {
			for(T2 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(T2... exclusions) {
			for(T2 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 contained
		 *                Any sub-groups to enclose in this group.
		 */
		@SafeVarargs
		public final void addSubgroup(T2 subgroup, T2... contained) {
			if(subgroup == null) {
				throw new NullPointerException("Subgroup marker must not be null");
			}

			Set<T2> contains = new HashSet<>();
			for(T2 contain : contained) {
				if(contain == null) {
					throw new NullPointerException("Contained group must not be null");
				}

				contains.add(contain);
			}

			subgroups.put(subgroup, contains);
		}

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

			builder.append("(");

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

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

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

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

			builder.append(" )");

			return builder.toString();
		}

	}

	/**
	 * The superclass for exceptions thrown during sequence delimitation.
	 */
	public static class DelimiterException extends RuntimeException {
		/**
		 * Create a new generic delimiter exception.
		 * 
		 * @param res
		 *                The reason for this exception.
		 */
		public DelimiterException(String res) {
			super(res);
		}
	}

	/*
	 * Mapping from opening delimiters to the names of the groups they open
	 */
	private Map<T, T> openDelimiters;

	/*
	 * Mapping from group names to actual groups.
	 */
	private Map<T, DelimiterGroup<T>> groups;

	/**
	 * Create a new sequence delimiter.
	 */
	public SequenceDelimiter() {
		openDelimiters = new HashMap<>();

		groups = new HashMap<>();
	}

	/**
	 * Convert a linear sequence into a tree that matches the delimiter
	 * structure.
	 * 
	 * Essentially, creates a parse tree of the expression against the
	 * following grammar while obeying the defined group rules.
	 * 
	 * <pre>
	 *         <tree>     -> (<data> | <subgroup> | <group>)*
	 *         <subgroup> -> <tree> <marker>
	 *         <group>    -> <open> <tree> <close>
	 *         
	 *         <data>     -> STRING
	 *         <open>     -> STRING
	 *         <close>    -> STRING
	 *         <marker>   -> STRING
	 * </pre>
	 * 
	 * @param seq
	 *                The sequence to delimit.
	 * 
	 * @param root
	 *                The root of the returned tree.
	 * 
	 * @param contents
	 *                The item to use to mark the contents of a group
	 * 
	 * @param subgroup
	 *                The item to use to mark a sub-group.
	 * 
	 * @return The sequence as a tree that matches its group structure. Each
	 *         node in the tree is either a data node, a subgroup node, or a
	 *         group node.
	 * 
	 *         A data node is a leaf node whose data is the string it
	 *         represents.
	 * 
	 *         A subgroup node is a node with two children, and the name of
	 *         the sub-group as its label. The first child is the contents
	 *         of the sub-group, and the second is the marker that started
	 *         the subgroup. The marker is a leaf node labeled with its
	 *         contents, and the contents contains a recursive tree.
	 * 
	 *         A group node is a node with three children, and the name of
	 *         the group as its label. The first child is the opening
	 *         delimiter, the second is the group contents, and the third is
	 *         the closing delimiter. The delimiters are leaf nodes labeled
	 *         with their contents, while the group node contains a
	 *         recursive tree.
	 * 
	 * @throws DelimiterException
	 *                 Thrown if something went wrong during sequence
	 *                 delimitation.
	 * 
	 */
	public ITree<T> delimitSequence(T root, T contents, T subgroup, @SuppressWarnings("unchecked") T... seq)
			throws DelimiterException {
		/*
		 * The root node of the tree to give back.
		 */
		ITree<T> res = new Tree<>(root);

		/*
		 * Handle the trivial case where there are no groups.
		 */
		if(openDelimiters.isEmpty()) {
			for(T tok : seq) {
				res.addChild(new Tree<>(tok));
			}

			return res;
		}

		/*
		 * The stack of trees that represent the sequence.
		 */
		Stack<ITree<T>> trees = new SimpleStack<>();
		trees.push(res);

		/*
		 * The stack of opened and not yet closed groups.
		 */
		Stack<DelimiterGroup<T>> groupStack = new SimpleStack<>();

		/*
		 * Groups that aren't allowed to be opened at the moment.
		 */
		Multiset<T> forbiddenDelimiters = HashMultiset.create();

		/*
		 * Map of who forbid what for debugging purposes.
		 */
		IMap<T, T> whoForbid = new PushdownMap<>();

		for(int i = 0; i < seq.length; i++) {
			T tok = seq[i];

			/*
			 * If we have an opening delimiter, handle it.
			 */
			if(openDelimiters.containsKey(tok)) {
				T groupName = openDelimiters.get(tok);
				DelimiterGroup<T> group = groups.get(groupName);

				/*
				 * Error on groups that can't open in this
				 * context.
				 * 
				 * This means groups that can't occur at the
				 * top-level of this group, as well as nested
				 * exclusions from all enclosing groups.
				 */
				if(isForbidden(groupStack, forbiddenDelimiters, groupName)) {
					StringBuilder msgBuilder = new StringBuilder();

					T forbiddenBy;

					if(whoForbid.containsKey(tok)) {
						forbiddenBy = whoForbid.get(tok);
					} else {
						forbiddenBy = groupStack.top().groupName;
					}

					String ctxList = StringUtils.toEnglishList(groupStack.toArray(), "then");

					msgBuilder.append("Group '");
					msgBuilder.append(group);
					msgBuilder.append("' can't be opened in this context.");
					msgBuilder.append(" (forbidden by '");
					msgBuilder.append(forbiddenBy);
					msgBuilder.append("')\nContext stack: ");
					msgBuilder.append(ctxList);

					throw new DelimiterException(msgBuilder.toString());
				}

				/*
				 * Add an open group.
				 */
				groupStack.push(group);

				/*
				 * The tree that represents the opened group.
				 */
				ITree<T> groupTree = new Tree<>(groupName);
				groupTree.addChild(new Tree<>(tok));

				/*
				 * The tree that represents the contents of the
				 * opened group.
				 */
				ITree<T> groupContents = new Tree<>(contents);

				/*
				 * Add the trees to the open trees.
				 */
				trees.push(groupTree);
				trees.push(groupContents);

				/*
				 * Add the nested exclusions from this group
				 */
				for(T exclusion : group.groupExclusions) {
					forbiddenDelimiters.add(exclusion);

					whoForbid.put(exclusion, groupName);
				}
			} else if(!groupStack.empty() && groupStack.top().isClosing(tok)) {
				/*
				 * Close the group.
				 */
				DelimiterGroup<T> closed = groupStack.pop();

				/*
				 * Remove the contents of the group and the
				 * group itself from the stack.
				 */
				ITree<T> contentTree = trees.pop();
				ITree<T> groupTree = trees.pop();

				/*
				 * Fill in the group node.
				 */
				groupTree.addChild(contentTree);
				groupTree.addChild(new Tree<>(tok));

				/*
				 * Add the group node to the group that
				 * contained it.
				 */
				trees.top().addChild(groupTree);

				/*
				 * Remove nested exclusions from this group.
				 */
				for(T excludedGroup : closed.groupExclusions) {
					forbiddenDelimiters.remove(excludedGroup);

					whoForbid.remove(excludedGroup);
				}
			} else if(!groupStack.empty() && groupStack.top().subgroups.containsKey(tok)){
				/*
				 * Parse a sub-group.
				 */
				
				/*
				 * The set of enclosed groups.
				 */
				Set<T> enclosed = groupStack.top().subgroups.get(tok);
				
				/*
				 * The current contents of this group.
				 */
				ITree<T> contentTree = trees.pop();
				
				/*
				 * Find the first element to enclose in the subgroup.
				 */
				int ind = contentTree.revFind((chd) -> {
					if(chd.getHead().equals(subgroup)) {
						return !enclosed.contains(chd.getChild(1));
					} else {
						return false;
					}
				});
				
				ITree<T> newContentTree = new Tree<>(contentTree.getHead());
				ITree<T> subgroupContents = new Tree<>(contents);
				
				/*
				 * Split content tree into an untouched tree, and the subgroup.
				 */
				for(int j = 0; j < contentTree.getChildrenCount(); j++) {
					ITree<T> child = contentTree.getChild(j);
					
					if(j < ind) {
						newContentTree.addChild(child);
					} else {
						subgroupContents.addChild(child);
					}
				}
				
				/*
				 * Construct the subgroup.
				 */
				ITree<T> subgroupTree = new Tree<>(subgroup);
				subgroupTree.addChild(subgroupContents);
				subgroupTree.addChild(new Tree<>(tok));
				
				/*
				 * Add the subgroup to the group.
				 */
				newContentTree.addChild(subgroupTree);
				
				/*
				 * Add the group contents.
				 */
				trees.push(newContentTree);
			} else {
				trees.top().addChild(new Tree<>(tok));
			}
		}

		/*
		 * Error if not all groups were closed.
		 */
		if(!groupStack.empty()) {
			DelimiterGroup<T> group = groupStack.top();
			StringBuilder msgBuilder = new StringBuilder();

			String closingDelims = StringUtils.toEnglishList(group.closingDelimiters.toArray(), false);

			String ctxList = StringUtils.toEnglishList(groupStack.toArray(), "then");

			msgBuilder.append("Unclosed group '");
			msgBuilder.append(group.groupName);
			msgBuilder.append("'. Expected one of ");
			msgBuilder.append(closingDelims);
			msgBuilder.append(" to close it\nOpen groups: ");
			msgBuilder.append(ctxList);

			throw new DelimiterException(msgBuilder.toString());
		}

		return res;
	}

	private boolean isForbidden(Stack<DelimiterGroup<T>> groupStack, Multiset<T> forbiddenDelimiters, T groupName) {
		boolean localForbid;
		if(groupStack.empty())
			localForbid = false;
		else
			localForbid = groupStack.top().topLevelExclusions.contains(groupName);

		return localForbid || forbiddenDelimiters.contains(groupName);
	}

	/**
	 * Add a open delimiter for the specified group.
	 * 
	 * @param open
	 *                The open delimiter.
	 * @param groupName
	 *                The name of the group it opens.
	 */
	public void addOpener(T open, T groupName) {
		if(open == null) {
			throw new NullPointerException("Opener must not be null");
		} else if(open.equals("")) {
			throw new IllegalArgumentException("Empty string is not a valid opening delimiter");
		} else if(groupName == null) {
			throw new NullPointerException("Group name must not be null");
		} else if(!groups.containsKey(groupName)) {
			throw new IllegalArgumentException("Group " + groupName + " doesn't exist.");
		}

		openDelimiters.put(open, groupName);
	}

	/**
	 * Add a delimiter group.
	 * 
	 * @param group
	 *                The delimiter group.
	 */
	public void addGroup(DelimiterGroup<T> group) {
		if(group == null) {
			throw new NullPointerException("Group must not be null");
		}

		groups.put(group.groupName, group);
	}

	/**
	 * Creates and adds a delimiter group using the provided settings.
	 * 
	 * @param openers
	 *                The tokens that open this group
	 * @param groupName
	 *                The name of the group
	 * @param closers
	 *                The tokens that close this group
	 */
	public void addGroup(T[] openers, T groupName, @SuppressWarnings("unchecked") T... closers) {
		DelimiterGroup<T> group = new DelimiterGroup<>(groupName);

		group.addClosing(closers);

		addGroup(group);

		for(T open : openers) {
			addOpener(open, groupName);
		}
	}
}