transcendental-lisp/src/eval/SYMBOL_FUNCTION.java

69 lines
2.1 KiB
Java
Raw Normal View History

2016-12-07 16:38:26 -05:00
/*
* Name: Mike Cifelli
* Course: CIS 443 - Programming Languages
* Assignment: Lisp Interpreter 2
*/
package eval;
import parser.*;
import sexpression.Cons;
import sexpression.SExpression;
import sexpression.Symbol;
2016-12-07 16:38:26 -05:00
/**
* <code>SYMBOL_FUNCTION</code> represents the SYMBOL-FUNCTION function in
* Lisp.
*/
public class SYMBOL_FUNCTION extends LispFunction {
// The number of arguments that SYMBOL-FUNCTION takes.
private static final int NUM_ARGS = 1;
public SExpression call(Cons argList) {
// retrieve the number of arguments passed to SYMBOL-FUNCTION
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("SYMBOL-FUNCTION"),
argList);
String errMsg = "too " +
((argListLength > NUM_ARGS) ? "many" : "few") +
" arguments given to SYMBOL-FUNCTION: " +
originalSExpr;
throw new RuntimeException(errMsg);
}
SExpression arg = argList.getCar();
// make sure the argument is a symbol
if (arg.symbolp()) {
LispFunction function = EVAL.lookupFunction(arg.toString());
// make sure the function actually exists
if (function != null) {
if (function instanceof UserDefinedFunction) {
2016-12-07 16:38:26 -05:00
// this is a user-defined function
UserDefinedFunction udFunction = (UserDefinedFunction) function;
2016-12-07 16:38:26 -05:00
return udFunction.getLexpr();
}
// this is a built-in function
return new Symbol("SUBR-" + arg.toString());
}
throw new RuntimeException("SYMBOL-FUNCTION: undefined function " +
arg);
}
throw new RuntimeException("SYMBOL-FUNCTION: " + arg +
" is not a symbol");
}
}