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

import java.util.function.UnaryOperator;

import bjc.pratt.ParserContext;
import bjc.pratt.commands.CommandResult;
import bjc.pratt.commands.CommandResult.Status;
import bjc.pratt.tokens.Token;
import bjc.data.Tree;
import bjc.utils.parserutils.ParserException;

/**
 * A parse block that can adjust the state before handling its context.
 *
 * @author bjculkin
 *
 * @param <K>
 *        The key type of the tokens.
 * @param <V>
 *        The value type of the tokens.
 * @param <C>
 *        The state type of the parser.
 */
public class TriggeredParseBlock<K, V, C> implements ParseBlock<K, V, C> {
	private final UnaryOperator<C> onEntr;
	private final UnaryOperator<C> onExt;

	private final ParseBlock<K, V, C> sourc;

	/**
	 * Create a new triggered parse block.
	 *
	 * @param onEnter
	 *        The action to fire before parsing the block.
	 *
	 * @param onExit
	 *        The action to fire after parsing the block.
	 *
	 * @param source
	 *        The block to use for parsing.
	 */
	public TriggeredParseBlock(final UnaryOperator<C> onEnter, final UnaryOperator<C> onExit,
			final ParseBlock<K, V, C> source) {
		onEntr = onEnter;
		onExt = onExit;
		sourc = source;
	}

	@Override
	public CommandResult<K, V> parse(final ParserContext<K, V, C> ctx) throws ParserException {
		final C newState = onEntr.apply(ctx.state);

		final ParserContext<K, V, C> newCtx = new ParserContext<>(ctx.tokens, ctx.parse, newState);

		final CommandResult<K,V> res = sourc.parse(newCtx);

		if (res.status != Status.SUCCESS) return res;
		
		ctx.state = onExt.apply(newState);

		return res;
	}

}