summaryrefslogtreecommitdiff
path: root/BJC-Utils2/src/main/java/bjc/utils/parserutils/ShuntingYard.java
blob: b30a69cd2cd1a58dfea0c999aabf8f5ed3bebf5e (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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package bjc.utils.parserutils;

import bjc.utils.funcdata.FunctionalList;
import bjc.utils.funcdata.FunctionalMap;
import bjc.utils.funcdata.IList;
import bjc.utils.funcdata.IMap;
import bjc.utils.funcutils.StringUtils;

import java.util.Deque;
import java.util.LinkedList;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * Utility to run the shunting yard algorithm on a bunch of tokens.
 *
 * @author ben
 *
 * @param <TokenType>
 *                The type of tokens being shunted.
 */
public class ShuntingYard<TokenType> {
	/**
	 * A enum representing the fundamental operator types.
	 *
	 * @author ben
	 *
	 */
	public static enum Operator implements IPrecedent {
		/**
		 * Represents addition.
		 */
		ADD(1),
		/**
		 * Represents subtraction.
		 */
		SUBTRACT(2),

		/**
		 * Represents multiplication.
		 */
		MULTIPLY(3),
		/**
		 * Represents division.
		 */
		DIVIDE(4);

		private final int precedence;

		private Operator(int prec) {
			precedence = prec;
		}

		@Override
		public int getPrecedence() {
			return precedence;
		}
	}

	private final class TokenShunter implements Consumer<String> {
		private IList<TokenType>		output;
		private Deque<String>			stack;
		private Function<String, TokenType>	transformer;

		public TokenShunter(IList<TokenType> outpt, Deque<String> stack,
				Function<String, TokenType> transformer) {
			this.output = outpt;
			this.stack = stack;
			this.transformer = transformer;
		}

		@Override
		public void accept(String token) {
			// Handle operators
			if(operators.containsKey(token)) {
				// Pop operators while there isn't a higher
				// precedence one
				while(!stack.isEmpty() && isHigherPrec(token, stack.peek())) {
					output.add(transformer.apply(stack.pop()));
				}

				// Put this operator onto the stack
				stack.push(token);
			} else if(StringUtils.containsOnly(token, "\\(")) {
				// Handle groups of parenthesis for multiple
				// nesting levels
				stack.push(token);
			} else if(StringUtils.containsOnly(token, "\\)")) {
				// Handle groups of parenthesis for multiple
				// nesting levels
				String swappedToken = token.replace(')', '(');

				// Remove tokens up to a matching parenthesis
				while(!stack.peek().equals(swappedToken)) {
					output.add(transformer.apply(stack.pop()));
				}

				// Remove the parenthesis
				stack.pop();
			} else {
				// Just add the transformed token
				output.add(transformer.apply(token));
			}
		}
	}

	/*
	 * Holds all the shuntable operations.
	 */
	private IMap<String, IPrecedent> operators;

	/**
	 * Create a new shunting yard with a default set of operators.
	 *
	 * @param configureBasics
	 *                Whether or not basic math operators should be
	 *                provided.
	 */
	public ShuntingYard(boolean configureBasics) {
		operators = new FunctionalMap<>();

		// Add basic operators if we're configured to do so
		if(configureBasics) {
			operators.put("+", Operator.ADD);
			operators.put("-", Operator.SUBTRACT);
			operators.put("*", Operator.MULTIPLY);
			operators.put("/", Operator.DIVIDE);
		}
	}

	/**
	 * Add an operator to the list of shuntable operators.
	 *
	 * @param operator
	 *                The token representing the operator.
	 * 
	 * @param precedence
	 *                The precedence of the operator to add.
	 */
	public void addOp(String operator, int precedence) {
		/*
		 * Create the precedence marker
		 */
		IPrecedent prec = IPrecedent.newSimplePrecedent(precedence);

		this.addOp(operator, prec);
	}

	/**
	 * Add an operator to the list of shuntable operators.
	 *
	 * @param operator
	 *                The token representing the operator.
	 * 
	 * @param precedence
	 *                The precedence of the operator.
	 */
	public void addOp(String operator, IPrecedent precedence) {
		/*
		 * Complain about trying to add an incorrect operator
		 */
		if(operator == null)
			throw new NullPointerException("Operator must not be null");
		else if(precedence == null) throw new NullPointerException("Precedence must not be null");

		/*
		 * Add the operator to the ones we handle
		 */
		operators.put(operator, precedence);
	}

	private boolean isHigherPrec(String left, String right) {
		// Check if the right operator exists
		boolean exists = operators.containsKey(right);

		// If it doesn't, the left is higher precedence.
		if(!exists) return false;

		// Get the precedence of operators
		int rightPrecedence = operators.get(right).getPrecedence();
		int leftPrecedence = operators.get(left).getPrecedence();

		// Evaluate what we were asked
		return rightPrecedence >= leftPrecedence;
	}

	/**
	 * Transform a string of tokens from infix notation to postfix.
	 *
	 * @param input
	 *                The string to transform.
	 * 
	 * @param transformer
	 *                The function to use to transform strings to tokens.
	 * 
	 * @return A list of tokens in postfix notation.
	 */
	public IList<TokenType> postfix(IList<String> input, Function<String, TokenType> transformer) {
		// Check our input
		if(input == null)
			throw new NullPointerException("Input must not be null");
		else if(transformer == null) throw new NullPointerException("Transformer must not be null");

		// Here's what we're handing back
		IList<TokenType> output = new FunctionalList<>();

		// The stack to put operators on
		Deque<String> stack = new LinkedList<>();

		// Shunt the tokens
		input.forEach(new TokenShunter(output, stack, transformer));

		// Transform any resulting tokens
		stack.forEach(token -> {
			output.add(transformer.apply(token));
		});

		return output;
	}

	/**
	 * Remove an operator from the list of shuntable operators.
	 *
	 * @param operator
	 *                The token representing the operator. If null, remove
	 *                all operators.
	 */
	public void removeOp(String operator) {
		// Check if we want to remove all operators
		if(operator == null) {
			operators = new FunctionalMap<>();
		} else {
			operators.remove(operator);
		}
	}
}