def test_calling_with_wrong_number_of_arguments():
    """Functions should raise exceptions when called with wrong number of arguments."""

    env = Environment()
    evaluate(parse("(def fn (lambda (p1 p2) 'what_ever))"), env)
    with assert_raises(LispError):
        evaluate(parse("(fn 1 2 3)"), env)
def test_calling_atom_raises_exception():
    """A function call to a non-function should result in an error."""

    with assert_raises(LispError):
        evaluate(parse("(True 'foo 'bar)"), Environment())
    with assert_raises(LispError):
        evaluate(parse("(42)"), Environment())
def test_lookup_missing_variable():
    """Referencing undefined variables should raise an appropriate exception.

    This test should already be working if you implemented the environment correctly."""

    with assert_raises(LispError):
        evaluate("my-var", Environment())
Пример #4
0
def test_lookup_missing_variable():
    """Referencing undefined variables should raise an appropriate exception.

    This test should already be working if you implemented the environment correctly."""

    with assert_raises(LispError):
        evaluate("my-var", Environment())
Пример #5
0
def test_combined_math_operators():
    """To be able to do anything useful, we need some combined math operators.

    Let us try stringing together some additions.
    """

    assert_equals(10, evaluate(parse("(+ (+ 1 2) (+ 3 4))"), Environment()))
    assert_equals(10.8123, evaluate(parse("(+ (+ 1.2 2.0123) (+ 3.5 4.1))"), Environment()))
Пример #6
0
def test_getting_tail_of_list():
    """`tail` returns the tail of the list.

    The tail is the list retained after removing the first element."""

    assert_equals("(2 3)", interpret("(tail '(1 2 3))", Environment()))
    assert_equals([2, 3], evaluate(parse("(tail '(1 2 3))"), Environment()))
    assert_equals([2, 3], evaluate(['tail', ['quote', [1, 2, 3]]], Environment()))
Пример #7
0
def test_getting_tail_of_rlist():
    """`tail` returns the reverse of the tail of the list.

    That is all the elements except the last."""

    assert_equals("(1 2)", interpret("(rtail '(1 2 3))", Environment()))
    assert_equals([1, 2], evaluate(parse("(rtail '(1 2 3))"), Environment()))
    assert_equals([1, 2], evaluate(['rtail', ['quote', [1, 2, 3]]], Environment()))
Пример #8
0
def test_checking_whether_list_is_empty():
    """The `empty` form checks whether or not a list is empty."""

    assert_equals(False, evaluate(parse("(empty '(1 2 3))"), Environment()))
    assert_equals(False, evaluate(parse("(empty '(1))"), Environment()))

    assert_equals(True, evaluate(parse("(empty '())"), Environment()))
    assert_equals(True, evaluate(parse("(empty (tail '(1)))"), Environment()))
def test_define_with_wrong_number_of_arguments():
    """Defines should have exactly two arguments, or raise an error"""

    with assert_raises(LispError):
        evaluate(parse("(def x)"), Environment())

    with assert_raises(LispError):
        evaluate(parse("(def x 1 2)"), Environment())
def test_variable_lookup_after_define():
    """Test define and lookup variable in same environment.

    This test should already be working when the above ones are passing."""

    env = Environment()
    evaluate(parse("(def foo (+ 2.1 2.1))"), env)
    assert_equals(4.2, evaluate("foo", env))
Пример #11
0
def test_variable_lookup_after_define():
    """Test define and lookup variable in same environment.

    This test should already be working when the above ones are passing."""

    env = Environment()
    evaluate(parse("(def foo (+ 2.1 2.1))"), env)
    assert_equals(4.2, evaluate("foo", env))
Пример #12
0
def test_define_with_wrong_number_of_arguments():
    """Defines should have exactly two arguments, or raise an error"""

    with assert_raises(LispError):
        evaluate(parse("(def x)"), Environment())

    with assert_raises(LispError):
        evaluate(parse("(def x 1 2)"), Environment())
def test_lambda_arguments_are_lists():
    """The parameters of a `lambda` should be a list."""

    closure = evaluate(parse("(lambda (x y) (+ x y))"), Environment())
    assert_true(is_list(closure.params))

    with assert_raises(LispError):
        evaluate(parse("(lambda not-a-list (body of fn))"), Environment())
Пример #14
0
def test_evaluating_quote():
    """When a call is done to the `quote` form, the argument should be returned without 
    being evaluated.

    (quote foo) -> foo
    """

    assert_equals("foo", evaluate(["quote", "foo"], Environment()))
    assert_equals([1, 2, False], evaluate(["quote", [1, 2, False]], Environment()))
    assert_equals([1, 2, 3], evaluate(parse("'(1 2 3)"), Environment()))
Пример #15
0
def test_evaluating_eq_function():
    """The `eq` form is used to check whether two expressions are the same atom."""

    assert_equals(True, evaluate(["eq", 1, 1], Environment()))
    assert_equals(False, evaluate(["eq", 1, 2], Environment()))
    assert_equals(True, evaluate(parse("(eq 'foo 'foo)"), Environment()))
    assert_equals(False, evaluate(parse("(eq 'foo 'bar)"), Environment()))

    # Lists are never equal, because lists are not atoms
    assert_equals(False, evaluate(parse("(eq '(1 2 3) '(1 2 3))"), Environment()))
def test_call_to_function_should_evaluate_arguments():
    """Call to function should evaluate all arguments.

    When a function is applied, the arguments should be evaluated before being bound
    to the parameter names."""

    env = Environment()
    closure = evaluate(parse("(lambda (a) (+ a 5))"), env)
    ast = [closure, parse("(if False 0 (+ 10 10))")]

    assert_equals(25, evaluate(ast, env))
def test_define():
    """Test of simple define statement.

    The `define` form is used to define new bindings in the environment.
    A `define` call should result in a change in the environment. What you
    return from evaluating the definition is not important (although it 
    affects what is printed in the REPL)."""

    env = Environment()
    evaluate(parse("(def x 100.25)"), env)
    assert_equals(100.25, env.lookup("x"))
def test_evaluating_call_to_closure():
    """The first case we'll handle is when the AST is a list with an actual closure
    as the first element.

    In this first test, we'll start with a closure with no arguments and no free
    variables. All we need to do is to evaluate and return the function body."""

    closure = evaluate(parse("(lambda () (+ 1 2))"), Environment())
    ast = [closure]
    result = evaluate(ast, Environment())
    assert_equals(3, result)
Пример #19
0
def test_define():
    """Test of simple define statement.

    The `define` form is used to define new bindings in the environment.
    A `define` call should result in a change in the environment. What you
    return from evaluating the definition is not important (although it 
    affects what is printed in the REPL)."""

    env = Environment()
    evaluate(parse("(def x 100.25)"), env)
    assert_equals(100.25, env.lookup("x"))
def test_evaluating_call_to_closure_with_free_variables():
    """The body should be evaluated in the environment from the closure.

    The function's free variables, i.e. those not specified as part of the parameter list,
    should be looked up in the environment from where the function was defined. This is
    the environment included in the closure. Make sure this environment is used when
    evaluating the body."""

    closure = evaluate(parse("(lambda (x) (+ x y))"), Environment({"y": 1}))
    ast = [closure, 0]
    result = evaluate(ast, Environment({"y": 2}))
    assert_equals(1, result)
def test_evaluating_call_to_closure_with_arguments():
    """The function body must be evaluated in an environment where the parameters are bound.

    Create an environment where the function parameters (which are stored in the closure)
    are bound to the actual argument values in the function call. Use this environment
    when evaluating the function body."""

    env = Environment()
    closure = evaluate(parse("(lambda (a b) (+ a b))"), env)
    ast = [closure, 4, 5]

    assert_equals(9, evaluate(ast, env))
def test_calling_very_simple_function_in_environment():
    """A call to a symbol corresponds to a call to its value in the environment.

    When a 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."""

    env = Environment()
    evaluate(parse("(def add (lambda (x y) (+ x y)))"), env)
    assert_is_instance(env.lookup("add"), Closure)

    result = evaluate(parse("(add 1 2)"), env)
    assert_equals(3, result)
Пример #23
0
def test_undefined_decorator():

    program2 = """(@inc
    (def power_2
    (lambda (n)
        (* n n)))
        )
    """

    env = Environment()
    second_ast = parse(program2)
    evaluate(second_ast, env)
    third_ast = parse("(power_2 3)")
    with assert_raises(LispError):
        assert_equals(10, evaluate(third_ast, env))
def test_calling_function_recursively():
    """Tests that a named function is included in the environment
    where it is evaluated."""

    env = Environment()
    evaluate(parse("""
        (def my-fn
            # A meaningless, but recursive, function
            (lambda (x)
                (if (eq x 0)
                    42
                    (my-fn (- x 1)))))
    """), env)

    assert_equals(42, evaluate(parse("(my-fn 0)"), env))
    assert_equals(42, evaluate(parse("(my-fn 10)"), env))
def test_lambda_closure_holds_function():
    """The closure contains the parameter list and function body too."""

    closure = evaluate(parse("(lambda (x y) (+ x y))"), Environment())

    assert_equals(["x", "y"], closure.params)
    assert_equals(["+", "x", "y"], closure.body)
def test_evaluating_symbol():
    """Symbols (other than True and False) are treated as variable references.

    When evaluating a symbol, the corresponding value should be looked up in the 
    environment."""

    env = Environment({"foo": 42})
    assert_equals(42, evaluate("foo", env))
def test_let_functionality():
    """Tests if functions can have sub-functions that are
    namespace specific using the classic 'let' functionality."""

    env = Environment()
    evaluate(parse("""
        (def summer 
            (lambda (a b) 
                (let plusr 
                    (lambda (i j) 
                        (+ i j)) 
                (plusr a b))))
        """), env)

    assert_equals(42, evaluate(parse("(summer 40 2)"), env))
    with assert_raises(LispError):
        evaluate(parse("(plusr 40 2)"), env)
Пример #28
0
def test_evaluating_symbol():
    """Symbols (other than True and False) are treated as variable references.

    When evaluating a symbol, the corresponding value should be looked up in the 
    environment."""

    env = Environment({"foo": 42})
    assert_equals(42, evaluate("foo", env))
def test_basic_if_statement():
    """If statements are the basic control structures.

    The `if` should first evaluate it's first argument. If this evaluates to true, then
    the second argument is evaluated and returned. Otherwise the third and last argument
    is evaluated and returned instead."""

    if_expression = parse("(if True 42 1000)")
    assert_equals(42, evaluate(if_expression, Environment()))
def test_calling_lambda_directly():
    """It should be possible to define and call functions directly.

    A lambda definition in the call position of an AST should be evaluated, and then
    evaluated as before."""

    ast = parse("((lambda (x) x) 42)")
    result = evaluate(ast, Environment())
    assert_equals(42, result)
Пример #31
0
def test_creating_longer_lists_with_only_cons():
    """`cons` needs to evaluate it's arguments.

    Like all the other special forms and functions in our language, `cons` is 
    call-by-value. This means that the arguments must be evaluated before we 
    create the list with their values."""

    result = evaluate(parse("(cons 3 (cons (- 4 2) (cons 1 '())))"), Environment())
    assert_equals(parse("(3 2 1)"), result)
def test_if_with_sub_expressions():
    """A final test with a more complex if expression.
    This test should already be passing if the above ones are."""

    if_expression = parse("""
        (if (> 1 2)
            (- 1000 1)
            (+ 40 (- 3 1)))
    """)
    assert_equals(42, evaluate(if_expression, Environment()))
def test_lambda_closure_keeps_defining_env():
    """The closure should keep a copy of the environment where it was defined.

    Once we start calling functions later, we'll need access to the environment
    from when the function was created in order to resolve all free variables."""

    env = Environment({"foo": 1, "bar": 2})
    ast = ["lambda", [], 42]
    closure = evaluate(ast, env)
    assert_equals(closure.env, env)
Пример #34
0
def test_creating_lists_by_quoting():
    """One way to create lists is by quoting.

    We have already implemented `quote` so this test should already be
    passing.

    The reason we need to use `quote` here is that otherwise the expression would
    be seen as a call to the first element -- `1` in this case, which obviously isn't
    even a function."""

    assert_equals([1, 2, 3, True], evaluate(parse("'(1 2 3 True)"), Environment()))
def test_print():
    """It is hard to capture standard out in a test, so this test will
    just make sure that print statements don't kill the build."""

    if_expression = parse("""
        (print "Hey there, fly droog 2"
            (if (> 1 2)
                (- 1000 1)
                (+ 40 (- 3 1))))
    """)
    assert_equals(42, evaluate(if_expression, Environment()))
def test_defining_lambda_with_error_in_body():
    """The function body should not be evaluated when the lambda is defined.

    The call to `lambda` should return a function closure holding, among other things
    the function body. The body should not be evaluated before the function is called."""

    ast = parse("""
            (lambda (x y)
                (function body ((that) would never) work))
    """)
    assert_is_instance(evaluate(ast, Environment()), Closure)
Пример #37
0
def test_decorator():
    """
    Simple test case of decorator
    """
    program1 = """
    (def inc
    (lambda (n)
        (+ n 1)))
    """
    program2 = """(@inc
    (def power_2
    (lambda (n)
        (* n n)))
        )
    """
    env = Environment()
    first_ast = parse(program1)
    second_ast = parse(program2)
    evaluate(first_ast, env)
    evaluate(second_ast, env)

    third_ast = parse("(power_2 3)")
    assert_equals(10, evaluate(third_ast, env))
def test_make_sure_arguments_to_functions_are_evaluated():
    """The arguments passed to functions should be evaluated

    We should accept parameters that are produced through function
    calls. If you are seeing stack overflows, e.g.

    RuntimeError: maximum recursion depth exceeded while calling a Python object

    then you should double-check that you are properly evaluating the passed
    function arguments."""

    env = Environment()
    res = evaluate(parse("((lambda (x) x) (+ 1 2))"), env)
    assert_equals(res, 3)