package function.builtin; import java.io.*; import java.text.MessageFormat; import environment.Environment; import function.*; import parser.LispParser; import sexpression.*; public class LOAD extends LispFunction { private ArgumentValidator argumentValidator; private Environment environment; public LOAD() { this.argumentValidator = new ArgumentValidator("LOAD"); this.argumentValidator.setExactNumberOfArguments(1); this.argumentValidator.setEveryArgumentExpectedType(LispString.class); this.environment = Environment.getInstance(); } public SExpression call(Cons argumentList) { argumentValidator.validate(argumentList); LispString quotedName = (LispString) argumentList.getCar(); String fileName = removeSurroundingQuotes(quotedName.toString()); return processFile(fileName); } private String removeSurroundingQuotes(String fileName) { return fileName.substring(1, (fileName.length() - 1)); } private SExpression processFile(String fileName) { boolean wasSuccessful = false; LispParser parser = attemptToCreateParserOnFile(fileName); if (parser != null) wasSuccessful = isSuccessfulEvaluation(parser); return wasSuccessful ? Symbol.T : Nil.getInstance(); } private LispParser attemptToCreateParserOnFile(String fileName) { LispParser parser = null; try { parser = new LispParser(new FileInputStream(fileName), fileName); } catch (FileNotFoundException e) { printCouldNotOpenFileMessage(fileName); } return parser; } private boolean isSuccessfulEvaluation(LispParser parser) { while (!parser.isEof()) { try { SExpression sexpr = parser.getNextSExpression(); EVAL.eval(sexpr); } catch (RuntimeException e) { printErrorMessage(e.getMessage()); return false; } } return true; } private void printCouldNotOpenFileMessage(String fileName) { String message = MessageFormat.format("could not open ''{0}''", fileName); printErrorMessage(message); } private void printErrorMessage(String errorMessage) { String message = MessageFormat.format("LOAD: {0}", errorMessage); environment.getErrorOutput().println(message); } }