package function.builtin; import java.io.FileInputStream; import java.io.FileNotFoundException; import function.LispFunction; import parser.LispParser; import sexpression.*; /** * LOAD 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.isEof()) { try { SExpression sexpr = parser.getNextSExpression(); EVAL.eval(sexpr); } catch (RuntimeException e) { System.out.println("LOAD: " + e.getMessage()); return Nil.getUniqueInstance(); } } // success! return Symbol.T; } }