Ejemplo n.º 1
0
def evaluate(ast, env):
    """Evaluate an Abstract Syntax Tree in the specified environment."""
    if is_boolean(ast) or is_integer(ast):
        return ast
    elif is_symbol(ast):
        return env.lookup(ast)

    if not is_atom(ast[0]):
        ast[0] = evaluate(ast[0], env)
    elif is_symbol(ast[0]):
        if ast[0] in keywords:
            return keywords[ast[0]](ast, env)
        elif ast[0] in math_operators:
            return eval_math(ast, env)
        else:
            ast[0] = env.lookup(ast[0])

    if is_closure(ast[0]):
        args = [evaluate(x, env) for x in ast[1:]]
        num_args = len(args)
        num_params = len(ast[0].params)
        if num_args != num_params:
            raise LispError('wrong number of arguments, expected %d got %d'
                    % (num_params, num_args))
        bindings = dict(zip(ast[0].params, args))
        return evaluate(ast[0].body, ast[0].env.extend(bindings))

    raise LispError('not a function: %s' % unparse(ast[0]))
Ejemplo n.º 2
0
def eval_if_statement(args, env):
    evalPredicate = evaluate(args[0],env)
    if not (is_boolean(evalPredicate)):
        raise LispError('predicate must return boolean value')
    if evalPredicate:
        return evaluate(args[1], env)
    else:
        return evaluate(args[2], env)
Ejemplo n.º 3
0
def unparse(ast):
    """Turns an AST back into lisp program source"""

    if is_boolean(ast):
        return "#t" if ast else "#f"
    elif is_list(ast):
        if len(ast) > 0 and ast[0] == "quote":
            return "'%s" % unparse(ast[1])
        else:
            return "(%s)" % " ".join([unparse(x) for x in ast])
    else:
        # integers or symbols (or lambdas)
        return str(ast)
Ejemplo n.º 4
0
def evaluate(ast, env):
	"""Evaluate an Abstract Syntax Tree in the specified environment."""

	if is_symbol(ast):
		return env.lookup(ast)
	elif is_boolean(ast) or is_integer(ast):
		return ast
	elif is_closure(ast):
		return evalClosure(ast, [], env)
	elif is_list(ast) and len(ast) > 0:
		first = ast[0]

		# handle string commands
		if isinstance(first, basestring):
			if first in commands:
				return evalCommand(first, ast[1:], env)
			# When a non-keyword symbol is the first element of the AST list, it is resolved to its value in
			# the environment (which should be a function closure). An AST with the variables
			# replaced with its value should then be evaluated instead.
			else:
				func = env.lookup(first)
				if not is_closure(func):
					raise LispError("Symbol %s must evaluate to a function" % first)

				ast[0] = func
				return evaluate(ast, env)
		# handle closure objects
		elif is_closure(first):
			return evalClosure(first, ast[1:], env)
		else: # otherwise - evaluate the first expression on the list
			firstEval = evaluate(first, env);
			if is_closure(firstEval): # if closure - treat the rest of the list as arguments
				return evalClosure(first, ast[1:], env)
			else : # not a closure, just evaluate the rest of the list and return the last expression
				if len(ast) > 1:
					return evaluate(ast[1:], env)
				else:
					return firstEval

	raise LispError("Invalid AST: %s" % ast)
Ejemplo n.º 5
0
def evaluate(ast, env):
    """Evaluate an Abstract Syntax Tree in the specified environment."""
    if is_boolean(ast):
	return ast
    elif is_integer(ast):
	return ast
    elif ast[0] in ['+', '-', '*', '/']:
	return eval_math(ast, env)
    elif is_list(ast):
	if ast[0] == "atom":
	    return is_atom(evaluate(ast[1], env))
	    #return is_atom(ast[1])
	elif ast[0] == "quote":
	    return ast[1]
	elif ast[0] == "eq":
	    assert_exp_length(ast, 3)
	    v1 = evaluate(ast[1], env)
	    v2 = evaluate(ast[2], env)
	    if not is_atom(v1) or not is_atom(v2):
		return False
	    else:
		return (v1 == v2)
Ejemplo n.º 6
0
def evaluate(ast, env):
	"""Evaluate an Abstract Syntax Tree in the specified environment.
	"""
	if is_boolean(ast) or is_integer(ast): # evaluate booleans and integers
		return ast
	elif is_symbol(ast): # evaluate symbols
		return env.lookup(ast)
	elif is_list(ast): # evaluate lists
		if is_closure(ast[0]): # evaluate closure
			return eval_closure(ast, env)
		elif ast[0] == 'quote': # evaluate quotes
			return ast[1]
		elif ast[0] == 'atom': # evaluate atoms
			return is_atom(evaluate(ast[1], env))
		elif ast[0] == 'eq': # evaluate equality
			return eval_eq(ast, env)
		# evaluate basic math operators:
		elif ast[0] in ['+', '-', '/', '*', 'mod', '>', '<', '=']:
			return eval_math(ast, env)
		elif ast[0] == 'if': # evaluate if expression
			return eval_if(ast, env)
		elif ast[0] == 'define': # evaluate define statement
			eval_define(ast, env)
		elif ast[0] == 'lambda': # evaluate lambda statement
			return eval_lambda(ast, env)
		elif ast[0] == 'cons': # evaluate cons statement
			return eval_cons(ast, env)
		elif ast[0] == 'head': # evaluate head statement
			return eval_head(ast, env)
		elif ast[0] == 'tail': # evaluate tail statement
			return eval_tail(ast, env)
		elif ast[0] == 'empty': # evaluate empty statement
			return eval_empty(ast, env)
		elif is_symbol(ast[0]) or is_list(ast[0]): # evaluate closure from env
			return eval_closure_env(ast, env)
		else:
			raise LispError('Argument is not a function!')
Ejemplo n.º 7
0
def evaluate(ast, env):
    """Evaluate an Abstract Syntax Tree in the specified environment."""

    # evaluating atoms
    if is_symbol(ast):
        return env.lookup(ast)
    if is_boolean(ast):
        return ast
    if is_integer(ast):
        return ast

    if is_list(ast):

        # lists
        if ast[0] == "cons":
            if len(ast) != 3:
                raise LispError("expected 2 arguments")
            else:
                value = evaluate(ast[1], env)
                list = evaluate(ast[2], env)
                new_list = [value]
                for i in list:
                    new_list.append(i)
                return new_list

        if ast[0] == "head":
            list = evaluate(ast[1], env)
            if list == []:
                raise LispError
            else: return list[0]

        if ast[0] == "tail":
            list = evaluate(ast[1], env)
            if list == []:

                raise LispError
            else: return list[1:]

        if ast[0] == "empty":
            list = evaluate(ast[1], env)
            if list == []:
                return True
            else: return False

        if ast[0] == "quote":
            return ast[1]
        # functions


        if is_closure(ast[0]):
            closure = ast[0]
            arguments = ast[1:]
            params = closure.params
            number_of_arguments = len(arguments)
            number_of_params = len(params)

            if number_of_arguments != number_of_params:
                raise LispError("wrong number of arguments, expected %(param)d got %(arg)d" %
                                {"arg": number_of_arguments, "param": number_of_params})
            variables = {}
            for i in range(number_of_arguments):
                arg = evaluate(arguments[i], env)
                param = params[i]
                variables.update({param: arg})
            environment = closure.env.extend(variables)

            return evaluate(closure.body, environment)

        if ast[0] == "lambda":
            if not is_list(ast[1]):
                raise LispError
            if len(ast) == 3:
                return Closure(env, ast[1], ast[2])
            else:
                raise LispError("number of arguments")

        # defining variables
        if ast[0] == "define":
            if is_symbol(ast[1]):
                if len(ast) == 3:
                    return env.set(ast[1], evaluate(ast[2], env))
                else:
                    raise LispError("Wrong number of arguments")
            else:
                raise LispError("non-symbol")

        #typechecks
        if ast[0] == "atom":
            return is_atom(evaluate(ast[1], env))
        if ast[0] == "eq":
            return evaluate(ast[1], env) == evaluate(ast[2], env) and \
                   is_atom(evaluate(ast[1], env)) and is_atom(evaluate(ast[2], env))

        #arithmetic:
        # elif is_arith_op(ast[0]):
        #     try:
        #         return arith_ops[ast[0]](evaluate(ast[1], env), evaluate(ast[2], env))
        # make dicitonary of these operators

        if ast[0] == "+":
            if is_integer(evaluate(ast[1], env)) and is_integer(evaluate(ast[2], env)):
                return evaluate(ast[1], env) + evaluate(ast[2], env)
            else:
                raise LispError
        if ast[0] == "-":
            if is_integer(evaluate(ast[1], env)) and is_integer(evaluate(ast[2], env)):
                return evaluate(ast[1], env) - evaluate(ast[2], env)
            else:
                raise LispError
        if ast[0] == "*":
            if is_integer(evaluate(ast[1], env)) and is_integer(evaluate(ast[2], env)):
                return evaluate(ast[1], env) * evaluate(ast[2], env)
            else:
                raise LispError
        if ast[0] == "/":
            if is_integer(evaluate(ast[1], env)) and is_integer(evaluate(ast[2], env)):
                return evaluate(ast[1], env) / evaluate(ast[2], env)
            else:
                raise LispError
        if ast[0] == "mod":
            if is_integer(evaluate(ast[1], env)) and is_integer(evaluate(ast[2], env)):
                return evaluate(ast[1], env) % evaluate(ast[2], env)
            else:
                raise LispError

        # boolean operators
        if ast[0] == ">":
            return evaluate(ast[1], env) > evaluate(ast[2], env)
        if ast[0] == "<":
            return evaluate(ast[1], env) < evaluate(ast[2], env)

        # control-flow
        if ast[0] == 'if':
            pred = ast[1]
            then = ast[2]
            elsee = ast[3]
            if evaluate(pred, env):
                return evaluate(then, env)
            else:
                return evaluate(elsee, env)

        if is_symbol(ast[0]) or is_list(ast[0]):
            closure = evaluate(ast[0], env)
            return evaluate([closure] + ast[1:], env)

        else:
            raise LispError("not a function")
Ejemplo n.º 8
0
def assert_boolean(p, exp=None):
    if not is_boolean(p):
        msg = "Boolean required, got '%s'. " % unparse(p)
        if exp is not None:
            msg += "Offending expression: %s" % unparse(exp)
        raise LispError(msg)
Ejemplo n.º 9
0
def evaluate(ast, env):
    """Evaluate an Abstract Syntax Tree in the specified environment."""
    if is_boolean(ast) or is_integer(ast):
        return ast
    elif is_symbol(ast):
        return env.lookup(ast)
    elif is_list(ast):
        f = ast[0]
        params = ast[1:]

        if is_list(f):
            c = evaluate(f, env)
            return evaluate([c] + params, env)
        elif f == 'quote':
            return params[0]
        elif f == 'atom':
            return is_atom(evaluate(params[0], env))
        elif f == 'if':
            test = evaluate(params[0], env)
            if not is_boolean(test):
                raise LispError("First argument to if must be boolean")

            if test:
                return evaluate(params[1], env)
            else:
                return evaluate(params[2], env)
        elif f == 'define':
            if len(params) != 2:
                raise LispError("Wrong number of arguments")
            elif not is_symbol(params[0]):
                raise LispError("First argument to define is a non-symbol")
            env.set(params[0], evaluate(params[1], env))
        elif f == 'lambda':
            if len(params) != 2:
                raise LispError("Wrong number of arguments")
            return Closure(env, params[0], params[1])
        elif is_closure(f):
            evaled_params = {}
            for i, symbol in enumerate(f.params):
                evaled_params[symbol] = evaluate(params[i], env)

            return evaluate(f.body, f.env.extend(evaled_params))
        elif is_symbol(f):
            evaled = evaluate(f, env)
            
            if callable(evaled):  # python function 
                evaled_params = []
                for p in params:
                    evaled_params.append(evaluate(p, env))
                return evaled(*evaled_params)
            elif is_closure(evaled):
                expected_arg_length = len(evaled.params)
                actual_arg_length = len(params)
                if expected_arg_length != actual_arg_length:
                    raise LispError("wrong number of arguments, expected " + str(expected_arg_length) + " got " + str(actual_arg_length))

                return evaluate([evaled] + params, env)
            else:
                raise LispError()
        else:
            raise LispError(str(ast) + "is not a function")
    else:
        raise LispError("xxx")
Ejemplo n.º 10
0
def evaluate(ast, env):
    """Evaluate an Abstract Syntax Tree in the specified environment."""

    # Simple types
    if is_symbol(ast):
        splitast = ast.split(' ')
        if splitast[0] == 'define':
            return Environment.extend(env, dict(zip(splitast[1:2], splitast[2::])))
        else:
            return Environment.lookup(env, ast)

    if is_boolean(ast) or is_integer(ast):
        return ast

    if is_list(ast):
        # Basic arithmetic
        if ast[0] == '+':
            if is_integer(evaluate(ast[1], env)) and is_integer(evaluate(ast[2], env)):
                return evaluate(ast[1], env) + evaluate(ast[2], env)
        if ast[0] == '-':
            if is_integer(evaluate(ast[1], env)) and is_integer(evaluate(ast[2], env)):
                return evaluate(ast[1], env) - evaluate(ast[2], env)
        if ast[0] == '/':
            if is_integer(evaluate(ast[1], env)) and is_integer(evaluate(ast[2], env)):
                return evaluate(ast[1], env) / evaluate(ast[2], env)
        if ast[0] == '*':
            if is_integer(evaluate(ast[1], env)) and is_integer(evaluate(ast[2], env)):
                return evaluate(ast[1], env) * evaluate(ast[2], env)
        if ast[0] == 'mod':
            if is_integer(evaluate(ast[1], env)) and is_integer(evaluate(ast[2], env)):
                return evaluate(ast[1], env) % evaluate(ast[2], env)
        if ast[0] == '>':
            if is_integer(evaluate(ast[1], env)) and is_integer(evaluate(ast[2], env)):
                return evaluate(ast[1], env) > evaluate(ast[2], env)
        if ast[0] == '<':
            if is_integer(evaluate(ast[1], env)) and is_integer(evaluate(ast[2], env)):
                return evaluate(ast[1], env) < evaluate(ast[2], env)

        # Atoms, quotes and equal
        if ast[0] == 'atom':
            return is_atom(evaluate(ast[1], env))
        if ast[0] == 'quote':
            return ast[1]
        if ast[0] == 'eq':
            return ( is_atom(evaluate(ast[1], env)) and is_atom(evaluate(ast[2], env))
                     and evaluate(ast[1], env) == evaluate(ast[2], env) )

        # If statement
        if ast[0] == 'if':
            if evaluate(ast[1], env) == True:
                return evaluate(ast[2], env)
            if evaluate(ast[1], env) == False:
                return evaluate(ast[3], env)

        # Lists
        if ast[0] == 'cons':
            head = evaluate(ast[1], env)
            tail = evaluate(ast[2], env)
            return [head] + tail

        if ast[0] == 'head':
            eval_new_ast = evaluate(ast[1], env)
            if eval_new_ast == []:
                raise LispError
            else:
                return eval_new_ast[0]

        if ast[0] == 'tail':
            eval_new_ast = evaluate(ast[1], env)
            if eval_new_ast == []:
                raise LispError
            else:
                return eval_new_ast[1:]

        if ast[0] == 'empty':
            if evaluate(ast[1], env) == []:
                return True
            else:
                return False

        # Functions
        if ast[0] == 'define':
            assert_valid_definition(ast[1:])
            symbol = ast[1]
            value = evaluate(ast[2], env)
            env.set(symbol, value)
            return symbol

        if ast[0] == 'lambda':
            if len(ast) != 3:
                raise LispError("Wrong number of arguments")
            if not is_list(ast[1]):
                raise LispError("Parameters are not in list-form")
            else:
                return Closure(env, ast[1], ast[2])

        if is_closure(ast[0]):
            closure = ast[0]
            arguments = ast[1:]
            if len(arguments) != len(closure.params):
               errormessage = "wrong number of arguments, expected " + str(len(closure.params)) + " got " + str(len(arguments))
               raise LispError(errormessage)
            arguments = [evaluate(a, env) for a in arguments]
            bindings = dict(zip(closure.params, arguments))
            new_env = closure.env.extend(bindings)
            return evaluate(closure.body, new_env)

        if is_list(ast[0]) or is_symbol(ast[0]):
                closure = evaluate(ast[0], env)
                return evaluate([closure] + ast[1:], env)

        else:
            raise LispError("not a function")

    else:
        raise LispError
Ejemplo n.º 11
0
def evaluate(ast, env):
    """Evaluate an Abstract Syntax Tree in the specified environment."""

    # evaluating booleans, integers, symbols and quotes
    if is_boolean(ast):
        return ast
    elif is_integer(ast):
        return ast
    elif is_symbol(ast):
        return env.lookup(ast)
    elif ast[0] == "quote":
        return ast[1]

    # everything else is of list form
    elif is_list(ast):

        # evaluating atom and eq functions
        if ast[0] == "atom":
            return is_atom(evaluate(ast[1], env))
        elif ast[0] == "eq":
            aste = [evaluate(s, env) for s in ast[1:]]
            return is_atom(aste[0]) and aste[0] == aste[1]

        # evaluating basic math operators
        elif ast[0] == "+":
            if is_integer(evaluate(ast[1], env)) and is_integer(evaluate(ast[2], env)):
                return evaluate(ast[1], env) + evaluate(ast[2], env)
            else:
                raise LispError('Arguments must be integers')

        elif ast[0] == "-":
            if is_integer(evaluate(ast[1], env)) and is_integer(evaluate(ast[2], env)):
                return evaluate(ast[1], env) - evaluate(ast[2], env)
            else:
                raise LispError('Arguments must be integers')

        elif ast[0] == "*":
            if is_integer(evaluate(ast[1], env)) and is_integer(evaluate(ast[2], env)):
                return evaluate(ast[1], env) * evaluate(ast[2], env)
            else:
                raise LispError('Arguments must be integers')

        elif ast[0] == "mod":
            if is_integer(evaluate(ast[1], env)) and is_integer(evaluate(ast[2], env)):
                return evaluate(ast[1], env) % evaluate(ast[2], env)
            else:
                raise LispError('Arguments must be integers')

        elif ast[0] == "/":
            if is_integer(evaluate(ast[1], env)) and is_integer(evaluate(ast[2], env)):
                return evaluate(ast[1], env) / evaluate(ast[2], env)
            else:
                raise LispError('Arguments must be integers')

        elif ast[0] == ">":
            return evaluate(ast[1], env) > evaluate(ast[2], env)
        elif ast[0] == "<":
            return evaluate(ast[1], env) < evaluate(ast[2], env)

        # Evaluating complex expressions

        # basic if statement
        elif ast[0] == 'if':
            if (evaluate(ast[1], env)) is True:
                return evaluate(ast[2], env)
            else:
                return evaluate(ast[3], env)

        # definitions of variables
        elif ast[0] == "define":
            if is_symbol(ast[1]):
                if len(ast) == 3:
                    return env.set(ast[1], evaluate(ast[2], env))
                else:
                    raise LispError("Wrong number of arguments")
            else:
                raise LispError("non-symbol")

        # evaluating a list in which the first element is a closure
        elif is_closure(ast[0]):
            closure = ast[0]
            arguments = ast[1:]
            parameters = closure.params

            if len(arguments) != len(parameters):
                raise LispError('wrong number of arguments, expected 2 got 3')

            bindings = {}
            for x in range(len(ast[1:])):
                arg1 = evaluate(arguments[x], env)
                param1 = parameters[x]
                bindings.update({param1: arg1})
            return evaluate(closure.body, closure.env.extend(bindings))

        elif ast[0] == 'lambda':
            if not is_list(ast[1]):
                raise LispError('not a list')
            if len(ast) == 3:
                return Closure(env, ast[1], ast[2])
            else:
                raise LispError('number of arguments')

        # new forms such as cons, head, tail and empty

        elif ast[0] == "cons":
            if len(ast) != 3:
                raise LispError("expected 2 arguments")
            else:
                list = [evaluate(x, env) for x in ast[1:]]
                return [list[0]] + list[1]

        elif ast[0] == "head":
            list = [evaluate(x, env) for x in ast[1:]]
            if list[0] == []:
                raise LispError('empty list')
            return list[0][0]

        elif ast[0] == "tail":
            list = evaluate(ast[1], env)
            if list == []:
                raise LispError('empty list')
            else:
                return list[1:]

        elif ast[0] == "empty":
            list = evaluate(ast[1], env)
            return (list == [])

        elif is_symbol(ast[0]) or is_list(ast[0]):
            closure = evaluate(ast[0], env)
            return evaluate([closure] + ast[1:], env)
        else:
            raise LispError("not a function")