blob: 3f2681bf1bcb119b456877a74572bc0c8e224079 (
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
|
package com.ashardalon.pratt.tokens;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import bjc.utils.funcutils.StringUtils;
/**
* A stream of tokens.
*
* @author EVE
*
* @param <K>
* The key type of the token.
*
* @param <V>
* The value type of the token.
*/
public abstract class TokenStream<K, V> implements Iterator<Token<K, V>> {
/**
* Get the current token.
*
* @return The current token.
*/
public abstract Token<K, V> current();
@Override
public abstract Token<K, V> next();
@Override
public abstract boolean hasNext();
/**
* Place a mark in the current stream, which can be either returned to or abandoned later on.
*/
public abstract void mark();
/**
* Reset the stream to the state it was in when the last mark was taken.
*/
public abstract void rollback();
/**
* Check if the stream has at least one mark.
*
* @return Whether or not at least one mark exists.
*/
public abstract boolean hasMark();
/**
* Remove the last mark placed into the stream. This prevents returning to it later on.
*/
public abstract void commit();
/**
* 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 ExpectionNotMet
* If the token is not one of the expected types.
*/
public void expect(final Set<K> expectedKeys) throws ExpectionNotMet {
final K curKey = current().getKey();
if(!expectedKeys.contains(curKey)) {
final String expectedList = StringUtils.toEnglishList(expectedKeys.toArray(), false);
throw new ExpectionNotMet("One of '" + expectedList + "' was expected, not " + curKey);
}
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 ExpectionNotMet
* If the token is not one of the expected types.
*/
@SafeVarargs
public final void expect(final K... expectedKeys) throws ExpectionNotMet {
HashSet<K> keys = new HashSet<>(Arrays.asList(expectedKeys));
expect(keys);
}
/**
* Check whether the head token is a certain type.
*
* @param val
* The type to check for.
*
* @return Whether or not the head token is of that type.
*/
public boolean headIs(final K val) {
return current().getKey().equals(val);
}
}
|