summaryrefslogtreecommitdiff
path: root/JPratt/src/main/java/bjc/pratt/blocks/ParseBlocks.java
blob: e0dea4860412edaea6e4dfc92b909b71d874b670 (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
package bjc.pratt.blocks;

import java.util.function.Predicate;
import java.util.function.UnaryOperator;

import bjc.pratt.ParseBlock;
import bjc.pratt.Token;
import bjc.utils.data.ITree;

/**
 * Utility class for creating common implementations of {@link ParseBlock}
 * 
 * @author bjculkin
 *
 */
public class ParseBlocks {
	/**
	 * Create a new repeating parse block.
	 * 
	 * @param inner
	 *                The parse block to repeat.
	 * 
	 * @param delim
	 *                The token type that seperates repetitions.
	 * 
	 * @param term
	 *                The token type that terminates repititions.
	 * 
	 * @param mark
	 *                The token to use as the node in the AST.
	 * 
	 * @param action
	 *                The action to perform on the state after every
	 *                repitition.
	 * 
	 * @return A configured repeating parse block.
	 */
	public static <K, V, C> ParseBlock<K, V, C> repeating(ParseBlock<K, V, C> inner, K delim, K term,
			Token<K, V> mark, UnaryOperator<C> action) {
		return new RepeatingParseBlock<>(inner, delim, term, mark, action);
	}

	/**
	 * Create a new triggered parse block.
	 * 
	 * @param source
	 *                The block to trigger around.
	 * 
	 * @param onEnter
	 *                The action to perform upon the state before entering
	 *                the block.
	 * 
	 * @param onExit
	 *                The action to perform upon the state after exiting the
	 *                block.
	 * 
	 * @return A configured trigger parse block.
	 */
	public static <K, V, C> ParseBlock<K, V, C> trigger(ParseBlock<K, V, C> source, UnaryOperator<C> onEnter,
			UnaryOperator<C> onExit) {
		return new TriggeredParseBlock<>(onEnter, onExit, source);
	}

	/**
	 * Create a new simple parse block.
	 * 
	 * @param precedence
	 *                The precedence of the expression inside the block.
	 * 
	 * @param terminator
	 *                The key type of the token expected after this block,
	 *                or null if none is expected.
	 * 
	 * @param validator
	 *                The predicate to use to validate parsed expressions,
	 *                or null if none is used.
	 * 
	 * @return A configured simple parse block.
	 */
	public static <K, V, C> ParseBlock<K, V, C> simple(int precedence, K terminator,
			Predicate<ITree<Token<K, V>>> validator) {
		return new SimpleParseBlock<>(precedence, terminator, validator);
	}
}