summaryrefslogtreecommitdiff
path: root/dice/src/example/java/bjc/dicelang/neodice/DieBoxCLI.java
blob: 557fd510888310d1127009641194c061fb962183 (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
package bjc.dicelang.neodice;

import static bjc.dicelang.neodice.statements.BooleanStatementValue.*;
import static bjc.dicelang.neodice.statements.VoidStatementValue.*;

import java.io.*;
import java.util.*;
import java.util.regex.*;

import bjc.data.*;
import bjc.dicelang.neodice.commands.*;
import bjc.dicelang.neodice.statements.*;
import bjc.funcdata.*;

/**
 * Command-line interface for testing the neodice implementation.
 * 
 * @author Ben Culkin
 *
 */
public class DieBoxCLI {
	private static final Pattern INT_PATTERN = Pattern.compile("(?:\\+|-)?\\d+");
  Scanner     input;
	public PrintStream output;
	
	public IMap<String, StatementValue> bindings = new FunctionalMap<>();

	public Random rng = new Random();
	
	static final IMap<String, Command> builtInCommands;
	static final IMap<String, Command> builtInliterals;
	
	final IMap<String, Command> commands;
	final IMap<String, Command> literals;
	
	private int numStatements = 0;

	/**
	 * Whether or not to print out a prompt before asking for input
	 */
	public boolean doPrompt = true;
	
	/**
	 * Whether or not to output the results of each command.
	 */
	public boolean doOutput = true;
	
	/**
	 * Should warning messages be printed?
	 */
	public boolean doWarn = true;
	
	static {
		// Initialize all of our literal-formers
		builtInliterals = new FunctionalMap<>();
		
		builtInliterals.put("void",
				new LiteralCommand(
						VOID_INST,
						"the unique instance of type VOID",
						"Returns a reference to the unique instance of type VOID."));
		builtInliterals.put("true",
		    new LiteralCommand(
		        TRUE_INST,
		        "the unique true value of type BOOLEAN",
		        "Returns a reference to the unique true instance of type BOOLEAN"));
		builtInliterals.put("false",
        new LiteralCommand(
            FALSE_INST,
            "the unique false value of type BOOLEAN",
            "Returns a reference to the unique false instance of type BOOLEAN"));
    
		builtInliterals.deepFreeze();
    
    // Initialize all of our built-in commands
		builtInCommands = new FunctionalMap<>();
    
		builtInCommands.put("show-bindings", new ShowBindingsCommand());
		builtInCommands.put("bind", new BindCommand());
		builtInCommands.put("polyhedral-die", new PolyhedralDieCommand());
		builtInCommands.put("roll", new RollCommand());
		builtInCommands.put("help", new HelpCommand());
		builtInCommands.deepFreeze();
	}
	
	/**
	 * Create a new CLI for interacting with dice.
	 * 
	 * @param input  The place to read input from.
	 * @param output The place to read output from.
	 */
	public DieBoxCLI(Scanner input, PrintStream output) {
		this.input  = input;
		this.output = output;
		
		this.commands = builtInCommands.extend();
		this.literals = builtInliterals.extend();
	}
	
	/**
	 * Create a new CLI for interacting with dice.
	 * 
	 * @param input  The place to read input from.
	 * @param output The place to read output from.
	 */
	public DieBoxCLI(InputStream input, OutputStream output) {
		this(new Scanner(input), new PrintStream(output));
	}

	/**
	 * Main method.
	 * 
	 * @param args Currently unused CLI arguments.
	 */
	public static void main(String[] args) {
		Scanner input      = new Scanner(System.in);
		PrintStream output = System.out;
		
		DieBoxCLI box = new DieBoxCLI(input, output);
		box.run();
	}

	private void run() {		
		if (doPrompt) {
			output.println("diebox CLI - enter 'help' for help, 'exit' to exit");
		}
		
		if (doPrompt) output.printf("diebox(%d)> ", numStatements);
		while(input.hasNextLine()) {			
			String nextLine = input.nextLine().trim();
			
			numStatements += 1;
			
			if (nextLine.equals(""))     continue;
			// @FIXME Nov 15th, 2020 Ben Culkin :HardcodeExit
			// Exit should not be hard-coded like this
			if (nextLine.equals("exit")) break;
			
			String[] lineWords = nextLine.split("\\s+");
			Iterator<String> wordIter = new ArrayIterator<>(lineWords);
			try {
				StatementValue val = runStatement(wordIter);
				
				if (doOutput) output.printf("%s%s\n", doPrompt ? "==> " : "", val);
			} catch (DieBoxException dbex) {
				output.printf("ERROR (in statement %d): %s\n",
						numStatements, dbex.getMessage());
				Throwable curEx = dbex.getCause();
				while (curEx != null) {
					output.printf("...caused by: %s\n", curEx);
					
					curEx = dbex.getCause();
				}
			} catch (Exception ex) {
				output.printf("INTERNAL ERROR (in statement %d): %s\n",
						numStatements, ex.getMessage());
				ex.printStackTrace(output);
			}
			
			if (doPrompt) output.printf("diebox(%d)> ", numStatements);
		}
		
		input.close();
		output.close();
	}

	public StatementValue runStatement(Iterator<String> words) {
		if (!words.hasNext()) {
			return VOID_INST;
		}
		
		String command = words.next().trim();
		
		if (command.startsWith("$")) {
			// All variable refs start with $
			String varName = command.substring(1);
			
			if (bindings.containsKey(varName)) {
				return bindings.get(varName);
			} else {
				// @TODO Nov 15th, 2020 Ben Culkin :Autovars
				// Perhaps something along the lines of 'auto-variables' (here
				// called 'spring-loaded variables') should be created? These
				// would be essentially values which invoke a given expression
				// whenever they are referenced.
				throw new DieBoxException("Attempted to reference non-existing variable %s", varName);
			}
		} else if (command.startsWith("#")) {
			// All literals/literal-formers start with #
			String actualCommand = command.substring(1);
			
			// Attempt to use a mapped literal/literal-former
			Command literalCommand = literals.get(actualCommand);
			if (literalCommand != null) {
				return literalCommand.execute(words, this);
			} else {
        if (INT_PATTERN.matcher(actualCommand).matches()) {
          try {
            int val = Integer.parseInt(actualCommand);
            
            return new IntegerStatementValue(val);
          } catch (NumberFormatException nfex) {
            throw new DieBoxException(nfex, "Improper integer literal (%s)", actualCommand);
          }
        } else {
          throw new DieBoxException("Unknown literal format (%s)", actualCommand);
        }
			}
		} else {
		  // Attempt to use a mapped command first
		  Command mapCommand = commands.get(command);
		  if (mapCommand != null) {
		    return mapCommand.execute(words, this);
		  } else {
  			throw new DieBoxException("Unknown command %s", command);
		  }
		}
	}
}