summaryrefslogtreecommitdiff
path: root/base/src/main/java/bjc/utils/patterns/PatternMatcher.java
blob: e2ae9f61405746c39aaf667923b967a642e2721a (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
package bjc.utils.patterns;

import bjc.data.*;

/**
 * Implements pattern-matching (of a sort) against a collection of patterns.
 * 
 * @author Ben Culkin
 * 
 * @param <ReturnType> The type returned by the pattern.
 */
public class PatternMatcher<ReturnType, InputType>
	implements IPatternMatcher<ReturnType, InputType> {
	private final ComplexPattern<ReturnType, Object, InputType>[] patterns;
	
	/**
	 * Create a new pattern matcher.
	 * 
	 * @param patterns The set of patterns to match against.
	 */
	@SuppressWarnings("unchecked")
	@SafeVarargs
	public PatternMatcher(ComplexPattern<ReturnType, ?, InputType>...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 = (ComplexPattern<ReturnType, Object, InputType>[]) patterns;
	}

	@Override
	public ReturnType matchFor(InputType input) throws NonExhaustiveMatch {
		for (ComplexPattern<ReturnType, Object, InputType> pattern : patterns) {
			IPair<Boolean, Object> matches = pattern.matches(input);
			if (matches.getLeft()) {
				pattern.apply(input, matches.getRight());
			}
		}
		
		throw new NonExhaustiveMatch("Non-exhaustive match against " + input);
	}
}