/* * Name: Mike Cifelli * Course: CIS 443 - Programming Languages * Assignment: Lisp Interpreter 1 */ package main; import parser.*; import sexpression.SExpression; import eval.*; import error.ErrorManager; import error.LispException; import java.io.*; import java.text.MessageFormat; /** * LispInterpreter is an interpreter for the Lisp programming * language. It takes the name of a file as a command-line argument, evaluates * the S-expressions found in the file and then prints the results to the * console. If no file name is provided at the command-line, this program will * read from standard input. */ public class LispInterpreter { private static final String GREETING = "SUNY Potsdam Lisp Interpreter - Version 4.4.3"; private static final String PROMPT = "~ "; public static final String ANSI_RESET = "\u001B[0m"; public static final String ANSI_GREEN = "\u001B[32m"; /** * Evaluate the S-expressions found in the file given as a command-line * argument and print the results to the console. If no file name was given, * retrieve the S-expressions from standard input. * * @param args * the command-line arguments: * */ public static void main(String[] args) { LispParser parser = null; boolean interactive = false; if (args.length > 0) { // a file name was given at the command-line, attempt to create a // 'LispParser' on it try { parser = new LispParser(new FileInputStream(args[0]), args[0]); } catch (FileNotFoundException e) { ErrorManager.generateError(new LispException() { private static final long serialVersionUID = 1L; @Override public int getSeverity() { return ErrorManager.CRITICAL_LEVEL; } @Override public String getMessage() { return e.getMessage(); } }); } } else { // no file name was given, create a 'LispParser' on standard input parser = new LispParser(System.in, "System.in"); interactive = true; System.out.println(GREETING); System.out.println(); System.out.print(PROMPT); } while (!parser.isEof()) { try { SExpression sexpr = parser.getNextSExpression(); String result = MessageFormat.format("{0}{1}{2}", ANSI_GREEN, EVAL.eval(sexpr), ANSI_RESET); LispInterpreter.erasePrompt(interactive); System.out.println(result); } catch (LispException e) { LispInterpreter.erasePrompt(interactive); ErrorManager.generateError(e); } catch (RuntimeException e) { LispInterpreter.erasePrompt(interactive); ErrorManager.generateError(new LispException() { private static final long serialVersionUID = 1L; @Override public int getSeverity() { return 0; } @Override public String getMessage() { return e.getMessage(); } }); } if (interactive) { System.out.print(PROMPT); } } System.out.println(); } private static void erasePrompt(boolean interactive) { if (interactive) { for (int i = 0; i < PROMPT.length(); i++) { System.out.print("\b"); } } } }