summaryrefslogtreecommitdiff
path: root/JPratt/src/main/java/com/ashardalon/pratt/commands/CommandResult.java
blob: 45c17886e7eb6efe8bb257c66d3ac464ebb86f8c (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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package com.ashardalon.pratt.commands;

import com.ashardalon.pratt.tokens.Token;

import bjc.data.Tree;

/**
 * Represents the result of executing a command.
 * 
 * @author bjcul
 *
 * @param <K> The key type of the tokens
 * @param <V> The value type of the tokens
 */
public class CommandResult<K, V> {
	/**
	 * Represents the status of a command execution
	 * 
	 * @author bjcul
	 *
	 */
	public static enum Status {
		/**
		 * The command successfully parsed.
		 */
		SUCCESS,
		/**
		 * The command failed, in a non-recoverable way
		 */
		FAIL,
		/**
		 * The command failed. Attempt recovery via backtracking
		 */
		BACKTRACK
	}

	/**
	 * The status of this command.
	 */
	public final Status status;
	
	private Tree<Token<K, V>> success;
	
	private CommandResult(Status status) {
		this.status = status;
	}

	/**
	 * Get the success value of this command, or null if it failed.
	 * 
	 * @return The success value of the command
	 */
	public Tree<Token<K, V>> success() {
		return success;
	}

	/**
	 * Create a success result
	 * 
	 * @param <K2> The key type of the token
	 * @param <V2> The value type of the token
	 * 
	 * @param succ The tree produced by the command
	 * 
	 * @return A command result representing a success
	 */
	public static <K2, V2> CommandResult<K2, V2> success(Tree<Token<K2, V2>> succ) {
		CommandResult<K2, V2> result = new CommandResult<>(Status.SUCCESS);
		result.success = succ;
		return result;
	}

	/**
	 * Create a non-backtracking failure result.
	 * 
	 * @param <K2> The key type of the token
	 * @param <V2> The value type of the token
	 * 
	 * @return A command result representing a non-backtracking fail
	 */
	public static <K2, V2> CommandResult<K2, V2> fail() {
		CommandResult<K2, V2> result = new CommandResult<>(Status.FAIL);
		return result;
	}

	/**
	 * Create a backtracking failure result.
	 * 
	 * @param <K2> The key type of the token
	 * @param <V2> The value type of the token
	 * 
	 * @return A command result representing a backtracking fail
	 */
	public static <K2, V2> CommandResult<K2, V2> backtrack() {
		CommandResult<K2, V2> result = new CommandResult<>(Status.BACKTRACK);
		return result;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("CommandResult [status=");
		builder.append(status);
		if (status == Status.SUCCESS) {
			builder.append(", success=");
			builder.append(success);
		}
		builder.append("]");
		return builder.toString();
	}
	
	
}