Commits

Roman Dawydkin committed ccc6baa

Fallback to stdout if no console available.

Comments (0)

Files changed (1)

src/toy/ConsoleShell.java

 package toy;
 
+import java.io.BufferedReader;
 import java.io.Console;
+import java.io.IOError;
+import java.io.IOException;
+import java.io.InputStreamReader;
 import java.io.PrintWriter;
 
 public class ConsoleShell
 {
+	private static final String PROMPT = "> ";
+	private static final String MESSAGE_PREFIX = "= ";
+	private static final String ERROR_PREFIX = "! ";
+
 	class ConsoleMessagePrinter implements MessagePrinter
 	{
 		public void printError(String msg) {
 			final PrintWriter writer = console.writer();
-			writer.print("! ");
+			writer.print(ERROR_PREFIX);
 			writer.println(msg);
 		}
 
 		public void printLine(String msg) {
 			final PrintWriter writer = console.writer();
-			writer.print(": ");
+			writer.print(MESSAGE_PREFIX);
 			writer.println(msg);
 		}
 	}
 
+	class StdoutMessagePrinter implements MessagePrinter
+	{
+		public void printError(String msg) {
+			System.err.print(ERROR_PREFIX);
+			System.err.println(msg);
+			System.err.flush();
+		}
+
+		public void printLine(String msg) {
+			System.out.print(MESSAGE_PREFIX);
+			System.out.println(msg);
+			System.out.flush();
+		}
+	}
+
 	final Console console;
 	private Interpreter interpreter;
+	private MessagePrinter printer;
+	private BufferedReader reader;
 
 	public static void main(String[] args) {
 		new ConsoleShell().run();
 
 	public ConsoleShell() {
 		console = System.console();
+		if (console != null) {
+			printer = new ConsoleMessagePrinter();
+		} else {
+			printer = new StdoutMessagePrinter();
+			reader = new BufferedReader(new InputStreamReader(System.in));
+		}
+		interpreter = new Interpreter(printer);
 	}
 
 	private void run() {
-		if (console == null) {
-			System.err.println("Cannot allocate console");
-			System.exit(1);
-		}
-		interpreter = new Interpreter(new ConsoleMessagePrinter());
 		for (;;) {
-			final String line = console.readLine("> ");
+			final String line = readLine();
 			if (line == null) {
 				break;
 			}
 			interpreter.eval(line);
 		}
 	}
+
+	private String readLine() {
+		if (console != null) {
+			return console.readLine(PROMPT);
+		} else {
+			System.out.print(PROMPT);
+			System.out.flush();
+			try {
+				return reader.readLine();
+			} catch (IOException ex) {
+				throw new IOError(ex);
+			}
+		}
+	}
 }