92 lines
2.9 KiB
Java
92 lines
2.9 KiB
Java
/*
|
|
* Name: Mike Cifelli
|
|
* Course: CIS 443 - Programming Languages
|
|
* Assignment: Lisp Interpreter 1
|
|
*/
|
|
|
|
package main;
|
|
|
|
import parser.*;
|
|
import eval.*;
|
|
import error.ErrorManager;
|
|
import java.io.*;
|
|
import java.text.MessageFormat;
|
|
|
|
/**
|
|
* <code>LispInterpreter</code> 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 1.0.1";
|
|
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:
|
|
* <ul>
|
|
* <li><code>args[0]</code> - file name (optional)</li>
|
|
* </ul>
|
|
*/
|
|
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(e.getMessage(), ErrorManager.CRITICAL_LEVEL);
|
|
}
|
|
} 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.eof()) {
|
|
try {
|
|
SExpression sexpr = parser.getSExpr();
|
|
String result = MessageFormat.format("{0}{1}{2}", ANSI_GREEN, EVAL.eval(sexpr), ANSI_RESET);
|
|
|
|
LispInterpreter.erasePrompt(interactive);
|
|
System.out.println(result);
|
|
} catch (RuntimeException e) {
|
|
LispInterpreter.erasePrompt(interactive);
|
|
ErrorManager.generateError(e.getMessage(), 2);
|
|
} catch (IOException e) {
|
|
ErrorManager.generateError(e.getMessage(), ErrorManager.CRITICAL_LEVEL);
|
|
}
|
|
|
|
if (interactive) {
|
|
System.out.print(PROMPT);
|
|
}
|
|
}
|
|
}
|
|
|
|
private static void erasePrompt(boolean interactive) {
|
|
if (interactive) {
|
|
for (int i = 0; i < PROMPT.length(); i++) {
|
|
System.out.print("\b");
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|