88 lines
2.6 KiB
Java
88 lines
2.6 KiB
Java
/*
|
|
* Name: Mike Cifelli
|
|
* Course: CIS 443 - Programming Languages
|
|
* Assignment: Lisp Interpreter 2
|
|
*/
|
|
|
|
package eval;
|
|
|
|
import parser.*;
|
|
import java.io.*;
|
|
|
|
/**
|
|
* <code>LOAD</code> represents the LOAD function in Lisp.
|
|
*/
|
|
public class LOAD extends LispFunction {
|
|
// The number of arguments that LOAD takes.
|
|
private static final int NUM_ARGS = 1;
|
|
|
|
public SExpression call(Cons argList) {
|
|
// retrieve the number of arguments passed to LOAD
|
|
int argListLength = LENGTH.getLength(argList);
|
|
|
|
// make sure we have received the proper number of arguments
|
|
if (argListLength != NUM_ARGS) {
|
|
Cons originalSExpr = new Cons(new Symbol("LOAD"), argList);
|
|
String errMsg = "too " +
|
|
((argListLength > NUM_ARGS) ? "many" : "few") +
|
|
" arguments given to LOAD: " + originalSExpr;
|
|
|
|
throw new RuntimeException(errMsg);
|
|
}
|
|
|
|
SExpression argCar = argList.getCar();
|
|
|
|
// make sure the argument is a string
|
|
if (! argCar.stringp()) {
|
|
throw new RuntimeException("LOAD: " + argCar + " is not a string");
|
|
}
|
|
|
|
LispString quotedName = (LispString) argCar;
|
|
String fileName = quotedName.toString();
|
|
|
|
// remove the surrounding quotes from the file name
|
|
fileName = fileName.substring(1, (fileName.length() - 1));
|
|
|
|
return processFile(fileName);
|
|
}
|
|
|
|
// Evaluate all the S-expressions found in the file with the specified
|
|
// name.
|
|
//
|
|
// Parameters: fileName - the name of the file to be evaluated
|
|
// Returns: 'T' if the file was processed successfully; 'NIL' otherwise
|
|
private SExpression processFile(String fileName) {
|
|
LispParser parser = null;
|
|
|
|
// attempt to create a new 'LispParser' on the specified file
|
|
try {
|
|
parser = new LispParser(new FileInputStream(fileName), fileName);
|
|
} catch (FileNotFoundException e) {
|
|
System.out.println("LOAD: could not open " + fileName);
|
|
|
|
return Nil.getUniqueInstance();
|
|
}
|
|
|
|
// attempt to evaluate all the S-expressions contained in the file
|
|
while (! parser.eof()) {
|
|
try {
|
|
SExpression sexpr = parser.getSExpr();
|
|
|
|
EVAL.eval(sexpr);
|
|
} catch (RuntimeException e) {
|
|
System.out.println("LOAD: " + e.getMessage());
|
|
|
|
return Nil.getUniqueInstance();
|
|
} catch (IOException e) {
|
|
System.out.println("LOAD: " + e.getMessage());
|
|
|
|
return Nil.getUniqueInstance();
|
|
}
|
|
}
|
|
|
|
// success!
|
|
return Symbol.T;
|
|
}
|
|
|
|
}
|