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

59 lines
1.8 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
2017-03-03 15:06:49 -05:00
import static table.FunctionTable.lookupFunction;
import java.text.MessageFormat;
import error.LispException;
2016-12-19 13:05:53 -05:00
import function.*;
import sexpression.*;
2016-12-07 16:38:26 -05:00
@FunctionNames({ "SYMBOL-FUNCTION" })
2016-12-07 16:38:26 -05:00
public class SYMBOL_FUNCTION extends LispFunction {
private ArgumentValidator argumentValidator;
2016-12-07 16:38:26 -05:00
public SYMBOL_FUNCTION() {
this.argumentValidator = new ArgumentValidator("SYMBOL-FUNCTION");
this.argumentValidator.setExactNumberOfArguments(1);
this.argumentValidator.setEveryArgumentExpectedType(Symbol.class);
}
2016-12-07 16:38:26 -05:00
public SExpression call(Cons argumentList) {
argumentValidator.validate(argumentList);
2016-12-07 16:38:26 -05:00
SExpression symbol = argumentList.getFirst();
2017-03-03 15:06:49 -05:00
LispFunction function = lookupFunction(symbol.toString());
2016-12-07 16:38:26 -05:00
if (function != null)
2017-02-27 14:54:31 -05:00
return createRepresentation(symbol, function);
2017-02-06 13:43:27 -05:00
throw new UndefinedSymbolFunctionException(symbol);
}
2016-12-07 16:38:26 -05:00
2017-02-27 14:54:31 -05:00
private SExpression createRepresentation(SExpression symbol, LispFunction function) {
if (function instanceof UserDefinedFunction)
return ((UserDefinedFunction) function).getLambdaExpression();
2017-02-27 14:54:31 -05:00
String typeIndicator = function instanceof LispSpecialFunction ? "SPECIAL-FUNCTION" : "FUNCTION";
return new Symbol(MessageFormat.format("#<{0} {1}>", typeIndicator, symbol));
}
public static class UndefinedSymbolFunctionException extends LispException {
2016-12-07 16:38:26 -05:00
private static final long serialVersionUID = 1L;
private SExpression function;
2016-12-07 16:38:26 -05:00
public UndefinedSymbolFunctionException(SExpression function) {
this.function = function;
2016-12-07 16:38:26 -05:00
}
@Override
public String getMessage() {
return MessageFormat.format("SYMBOL-FUNCTION: undefined function: {0}", function);
}
2016-12-07 16:38:26 -05:00
}
}