summaryrefslogtreecommitdiff
path: root/dice/src/example/java/bjc/dicelang/neodice/commands/Command.java
blob: 8460104a8546d9c249feaf02aef7428d4bee4111 (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
package bjc.dicelang.neodice.commands;

import java.util.*;
import java.util.function.*;

import bjc.dicelang.neodice.*;
import bjc.dicelang.neodice.statements.*;

/**
 * A single CLI command.
 * 
 * @author Ben Culkin
 *
 */
@FunctionalInterface
public interface Command {
	/**
	 * Execute this command.
	 * 
	 * @param words The remaining input.
	 * @param state The current state.
	 * 
	 * @return The result of executing this command.
	 */
	public StatementValue execute(Iterator<String> words, DieBoxCLI state);
	
	/**
	 * Get the 'short help' or usage summary for this command.
	 * 
	 * @return The short help for this command.
	 */
	default String shortHelp() {
		return "no short help";
	}
	
	/**
	 * Get the 'long help' or detailed usage for this command.
	 * 
	 * @return The long help for this command.
	 */
	default String longHelp() {
		return "no long help";
	}
	
	/**
	 * Create a new command, backed by a function.
	 * 
	 * @param executor The function which backs the command.
	 * @param shortHelp The short help string.
	 * @param longHelp The long help string.
	 * 
	 * @return A command backed by the function, with help.
	 */
	static Command newCommand(
			BiFunction<Iterator<String>, DieBoxCLI, StatementValue> executor,
			String shortHelp, String longHelp) {
		return new FunctionalCommand(executor, shortHelp, longHelp);
	}
}

class FunctionalCommand implements Command {
	private final BiFunction<Iterator<String>, DieBoxCLI, StatementValue> executor;
	private final String shortHelp;
	private final String longHelp;
	
	public FunctionalCommand(
			BiFunction<Iterator<String>, DieBoxCLI, StatementValue> executor, String shortHelp,
			String longHelp) {
		this.executor = executor;
		this.shortHelp = shortHelp;
		this.longHelp = longHelp;
	}

	@Override
	public StatementValue execute(Iterator<String> words, DieBoxCLI state) {
		return executor.apply(words, state);
	}
	
	@Override
	public String shortHelp() {
		return shortHelp;
	}
	
	@Override
	public String longHelp() {
		return longHelp;
	}
}