transcendental-lisp/src/function/builtin/LOAD.java

85 lines
2.4 KiB
Java
Raw Normal View History

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