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
|
package bjc.utils.patterns;
import java.util.*;
import bjc.data.*;
/**
* A pattern matcher over a mutable set of patterns.
*
* Note that modifying a pattern matcher while it is currently doing pattern
* matching is a wonderful way to cause strange behavior.
*
* @author Ben Culkin
*
* @param <ReturnType> The type returned by the pattern matcher.
* @param <InputType> The type of the input to match against.
*/
public class MutablePatternMatcher<ReturnType, InputType>
implements PatternMatcher<ReturnType, InputType> {
private final List<ComplexPattern<ReturnType, Object, InputType>> patterns;
/**
* Create a new mutable pattern matcher with no patterns.
*/
public MutablePatternMatcher() {
patterns = new ArrayList<>();
}
/**
* Create a new mutable pattern matcher with the given set of patterns.
*
* @param patterns The set of patterns to match on.
*/
@SuppressWarnings("unchecked")
public MutablePatternMatcher(ComplexPattern<ReturnType, ?, InputType>... patterns) {
this();
for (ComplexPattern<ReturnType, ?, InputType> pattern : patterns) {
// Note: this may seem a somewhat questionable cast, but because we never
// actually do anything with the value who has a type matching the second
// parameter, this should be safe
this.patterns.add((ComplexPattern<ReturnType, Object, InputType>) pattern);
}
}
@Override
public ReturnType matchFor(InputType input) throws NonExhaustiveMatch {
Iterator<ComplexPattern<ReturnType, Object, InputType>> iterator;
iterator = new NonCMEIterator<>(patterns);
while(iterator.hasNext()) {
ComplexPattern<ReturnType, Object, InputType> pattern = iterator.next();
Pair<Boolean, Object> matches = pattern.matches(input);
matches.doWith((bool, obj) -> {
if (bool) pattern.apply(input, obj);
});
}
throw new NonExhaustiveMatch("Non-exhaustive match against " + input);
}
/**
* Add a pattern to this pattern matcher.
*
* @param pattern The pattern to add.
*
* @return Whether or not the pattern was added.
*/
@SuppressWarnings("unchecked")
public boolean addPattern(ComplexPattern<ReturnType, ?, InputType> pattern) {
return patterns.add((ComplexPattern<ReturnType, Object, InputType>) pattern);
}
/**
* Remove a pattern from this pattern matcher.
*
* @param pattern The pattern to remove.
*
* @return Whether or not the pattern was removed.
*/
@SuppressWarnings("unlikely-arg-type")
public boolean removePattern(ComplexPattern<ReturnType, ?, InputType> pattern) {
return patterns.remove(pattern);
}
}
|