summaryrefslogtreecommitdiff
path: root/dice-lang/src/bjc/dicelang/DiceLangConsole.java
blob: bbf3db8ab22c3e263e4e2c811aefe0e242ad7b48 (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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
package bjc.dicelang;

import static bjc.dicelang.Errors.ErrorKey.EK_CONS_INVDEFINE;
import static bjc.dicelang.Errors.ErrorKey.EK_CONS_INVPRAG;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jline.ConsoleReader;
import jline.Terminal;

/**
 * CLI interface to DiceLang
 *
 * @author EVE
 *
 */
public class DiceLangConsole {
	private int commandNumber;

	private final DiceLangEngine eng;

	private ConsoleReader read;

	/**
	 * Create a new console.
	 *
	 * @param args
	 *                The CLI args for the console.
	 */
	public DiceLangConsole(final String[] args) {
		commandNumber = 0;

		eng = new DiceLangEngine();

		if (!CLIArgsParser.parseArgs(args, eng)) {
			System.exit(1);
		}

		Terminal.setupTerminal();
	}

	/**
	 * Run the console.
	 */
	public void run() {
		/*
		 * Set up console.
		 */
		try {
			read = new ConsoleReader();
		} catch (final IOException ioex) {
			System.out.println("ERROR: Console init failed");
			return;
		}

		System.out.println("dice-lang v0.2");

		String comm = null;

		/*
		 * Read initial command.
		 */
		try {
			comm = read.readLine(String.format("(%d) dice-lang> ", commandNumber));
		} catch (final IOException ioex) {
			System.out.println("ERROR: I/O failed");
			return;
		}

		/*
		 * Run commands.
		 */
		while (!comm.equals("quit") && !comm.equals("exit")) {
			if (comm.startsWith("pragma")) {
				/*
				 * Run pragmas.
				 */
				final boolean success = handlePragma(comm.substring(7)); 

				if (success) {
					System.out.println("Pragma completed succesfully");
				} else {
					System.out.println("Pragma execution failed");
				}
			} else {
				/*
				 * Run commands.
				 */
				if(eng.debugMode)
					System.out.printf("\tRaw command: %s\n", comm);

				final boolean success = eng.runCommand(comm);

				if (success) {
					System.out.println("Command completed succesfully");
				} else {
					System.out.println("Command execution failed");
				}

				commandNumber += 1;
			}

			try {
				comm = read.readLine(String.format("(%d) dice-lang> ", commandNumber));
			} catch (final IOException ioex) {
				System.out.println("ERROR: I/O failed");
				return;
			}
		}
	}

	private boolean handlePragma(final String pragma) {
		if(eng.debugMode)
			System.out.println("\tRaw pragma: " + pragma);

		/*
		 * Grab the name from the arguments.
		 */
		String pragmaName = null;
		final int firstIndex = pragma.indexOf(' ');

		/*
		 * Handle argless pragmas.
		 */
		if (firstIndex == -1) {
			pragmaName = pragma;
		} else {
			pragmaName = pragma.substring(0, firstIndex);
		}

		/*
		 * Run pragmas.
		 */
		switch (pragmaName) {
		case "debug":
			System.out.println("\tDebug mode is now " + eng.toggleDebug());
			break;

		case "postfix":
			System.out.println("\tPostfix mode is now " + eng.togglePostfix());
			break;

		case "prefix":
			System.out.println("\tPrefix mode is now " + eng.togglePrefix());
			break;

		case "stepeval":
			System.out.println("\tStepeval mode is now" + eng.toggleStepEval());
			break;

		case "define":
			return defineMode(pragma.substring(7));

		case "help":
			return helpMode(pragma.substring(5));

		default:
			Errors.inst.printError(EK_CONS_INVPRAG, pragma);
			return false;
		}

		return true;
	}

	/*
	 * Run a help mode.
	 */
	private static boolean helpMode(final String pragma) {
		switch (pragma.trim()) {
		case "help":
			System.out.println("\tGet help on pragmas");
			break;

		case "debug":
			System.out.println("\tToggle debug mode. (Output stage results)");
			break;

		case "postfix":
			System.out.println("\tToggle postfix mode. (Don't shunt tokens)");
			break;

		case "prefix":
			System.out.println("\tToggle prefix mode. (Reverse token order instead of shunting)");
			break;

		case "stepeval":
			System.out.println("\tToggle stepeval mode. (Print out evaluation progress)");
			break;

		case "define":
			System.out.println("\tAdd a macro rewrite directive.");
			System.out.println("\tdefine <priority> <type> <recursion> <guard> <circular> <patterns>...");
			break;

		default:
			System.out.println("\tNo help available for pragma " + pragma);
		}

		// Help always works
		return true;
	}

	/*
	 * Matches slash-delimited strings (like /text/ or /text\/text/) Uses
	 * the "normal* (special normal*)*" pattern style recommended in
	 * 'Mastering regular expressions' Here, the normal is 'anything but a
	 * forward or backslash' (in regex, thats '[^/\\]') and the special is
	 * 'an escaped forward slash' (in regex, thats '\\\\/')
	 *
	 * Then, we just follow the pattern, escape it for java strings, and add
	 * the enclosing slashes
	 */
	private final Pattern slashPattern = Pattern.compile("/((?:\\\\.|[^/\\\\])*)/");

	private boolean defineMode(final String defineText) {
		/*
		 * Grab all of the separator spaces.
		 */
		final int firstIndex = defineText.indexOf(' ');
		final int secondIndex = defineText.indexOf(' ', firstIndex + 1);
		final int thirdIndex = defineText.indexOf(' ', secondIndex + 1);
		final int fourthIndex = defineText.indexOf(' ', thirdIndex + 1);
		final int fifthIndex = defineText.indexOf(' ', fourthIndex + 1);
		final int sixthIndex = defineText.indexOf(' ', fifthIndex + 1);

		/*
		 * Error if we got something we didn't need.
		 */
		if (firstIndex == -1) {
			Errors.inst.printError(EK_CONS_INVDEFINE, "(no priority)");
			return false;
		} else if (secondIndex == -1) {
			Errors.inst.printError(EK_CONS_INVDEFINE, "(no define type)");
			return false;
		} else if (thirdIndex == -1) {
			Errors.inst.printError(EK_CONS_INVDEFINE, "(no recursion type)");
			return false;
		} else if (fourthIndex == -1) {
			Errors.inst.printError(EK_CONS_INVDEFINE, "(no guard type)");
			return false;
		} else if (fifthIndex == -1) {
			Errors.inst.printError(EK_CONS_INVDEFINE, "(no circularity)");
			return false;
		} else if (sixthIndex == -1) {
			Errors.inst.printError(EK_CONS_INVDEFINE, "(no patterns)");
			return false;
		}

		final int priority = Integer.parseInt(defineText.substring(0, firstIndex));

		final String defineType = defineText.substring(firstIndex + 1, secondIndex);

		Define.Type type;
		boolean subMode = false;

		switch (defineType) {
		case "line":
			type = Define.Type.LINE;
			break;

		case "token":
			type = Define.Type.TOKEN;
			break;

		case "subline":
			type = Define.Type.LINE;
			subMode = true;
			break;

		case "subtoken":
			type = Define.Type.TOKEN;
			subMode = true;
			break;

		default:
			Errors.inst.printError(EK_CONS_INVDEFINE, "(unknown type)");
			return false;
		}

		final boolean doRecur = defineText.substring(secondIndex + 1,
		                        thirdIndex).equalsIgnoreCase("true");
		final boolean hasGuard = defineText.substring(thirdIndex + 1,
		                         fourthIndex).equalsIgnoreCase("true");
		final boolean isCircular = defineText.substring(thirdIndex + 1,
		                           fourthIndex).equalsIgnoreCase("true");

		final String pats = defineText.substring(fifthIndex + 1).trim();
		final Matcher patMatcher = slashPattern.matcher(pats);

		String guardPattern = null;

		if (hasGuard) {
			if (!patMatcher.find()) {
				Errors.inst.printError(EK_CONS_INVDEFINE, "(no guard pattern)");
				return false;
			}

			guardPattern = patMatcher.group(1);
		}

		if (!patMatcher.find()) {
			Errors.inst.printError(EK_CONS_INVDEFINE, "(no search pattern)");
			return false;
		}

		final String searchPattern = patMatcher.group(1);
		final List<String> replacePatterns = new LinkedList<>();

		while (patMatcher.find()) {
			replacePatterns.add(patMatcher.group(1));
		}

		final Define dfn = new Define(priority, subMode, doRecur, isCircular, guardPattern,
		                              searchPattern,
		                              replacePatterns);

		if (dfn.inError) return false;

		if (type == Define.Type.LINE) {
			eng.addLineDefine(dfn);
		} else {
			eng.addTokenDefine(dfn);
		}

		return true;
	}

	/**
	 * Main method.
	 *
	 * @param args
	 *                CLI arguments.
	 */
	public static void main(final String[] args) {
		final DiceLangConsole console = new DiceLangConsole(args);

		console.run();
	}
}