summaryrefslogtreecommitdiff
path: root/BJC-Utils2/src/main/java/bjc/utils/parserutils/pratt/TokenStream.java
blob: 8decc097cabdbb6f75dd53674147a1610ce7a550 (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
package bjc.utils.parserutils.pratt;

import bjc.utils.funcutils.StringUtils;
import bjc.utils.parserutils.ParserException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * A stream of tokens.
 * 
 * @author EVE
 *
 * @param <K>
 *                The key type of the token.
 * 
 * @param <V>
 *                The value type of the token.
 */
public interface TokenStream<K, V> {
	/**
	 * The exception thrown when an expectation fails.
	 * 
	 * @author EVE
	 *
	 */
	public static class ExpectationException extends ParserException {
		/**
		 * Create a new exception with the specified message.
		 * 
		 * @param msg
		 *                The message of the exception.
		 */
		public ExpectationException(String msg) {
			super(msg);
		}
	}

	/**
	 * Get the current token.
	 * 
	 * @return The current token.
	 */
	Token<K, V> current();

	/**
	 * Advance to the next token in the stream.
	 * 
	 * Has no effect when the end of the stream is reached.
	 */
	void next();

	/**
	 * Utility method for checking that the next token is one of a specific
	 * set of types, and then consuming it.
	 * 
	 * @param expectedKeys
	 *                The expected values
	 * 
	 * @throws ExpectationException
	 *                 If the token is not one of the expected types.
	 */
	default void expect(Set<K> expectedKeys) throws ExpectationException {
		K curKey = current().getKey();

		if(!expectedKeys.contains(curKey)) {
			String expectedList = StringUtils.toEnglishList(expectedKeys.toArray(), false);

			throw new ExpectationException("One of '" + expectedList + "' was expected, not " + curKey);
		} else {
			next();
		}
	}

	/**
	 * Utility method for checking that the next token is one of a specific
	 * set of types, and then consuming it.
	 * 
	 * @param expectedKeys
	 *                The expected values
	 * 
	 * @throws ExpectationException
	 *                 If the token is not one of the expected types.
	 */
	default void expect(@SuppressWarnings("unchecked") K... expectedKeys) throws ExpectationException {
		expect(new HashSet<>(Arrays.asList(expectedKeys)));
	}
}