Exemple #1
0
def test_defining_functions():
    prog = dsl_parse(
        "( (defun add-3 (un val int) ((x (un val int))) (apply + x 3))  (apply add-3 7) )"
    )
    assert evaluate(base_env(), prog) == 10

    prog = dsl_parse(
        "( (defvar x (un val foobar) 0) "
        "(set x 1000) "
        "(defun add-3 (un val int) ((x (un val int))) (apply + x 3))"
        "(apply add-3 7))")
    assert evaluate(base_env(), prog) == 10

    prog = dsl_parse(
        "( (defvar x (un val foobar) 0) "
        "(set x 1000) "
        "(defun add-3 (un val int) ((x (un val int))) (apply + x 3))"
        "(apply add-3 7) x)")
    assert evaluate(base_env(), prog) == 1000

    prog = dsl_parse(
        "( (defvar x (un val foobar) 0) "
        "(set x 1000) "
        "(defun add-3 (un val int) ((x (un val int))) (apply + x 3))"
        "(apply add-3 x))")
    assert evaluate(base_env(), prog) == 1003

    prog = dsl_parse(
        "( (defun add-3 (un val int) ((x (un val int))) (apply + x 3))  "
        "(defun add-4 (un val int) ((x (un val int))) (apply add-3 (apply + x 1)))"
        "(apply add-4 6) )")
    assert evaluate(base_env(), prog) == 10
Exemple #2
0
def main():
    print "Blogmath-Interpreter"

    if len(sys.argv) > 1:
        # Execute file
        filenames = sys.argv[1:]
        print "Executing %s..." % ", ".join(filenames)

        c = interpreter.Context()

        for filename in filenames:
            buf = open(filename).read()
            for _ in interpreter.evaluate(buf, c):
                pass
    else:
        # Start REPL interface
        print "('quit' or CTRL-C to terminate)"
        c = interpreter.Context()
        try:
            while True:
                try:
                    s = raw_input("> ")
                except EOFError:
                    print
                    continue

                if s == "quit":
                    break

                for output in interpreter.evaluate(s, c):
                    print output
        except KeyboardInterrupt:
            pass
Exemple #3
0
def main():
    print "Blogmath-Interpreter"
    
    if len(sys.argv) > 1:
        # Execute file
        filenames = sys.argv[1:]
        print "Executing %s..." % ", ".join(filenames)
        
        c = interpreter.Context()
        
        for filename in filenames:
            buf = open(filename).read()
            for _ in interpreter.evaluate(buf, c):
                pass
    else:
        # Start REPL interface
        print "('quit' or CTRL-C to terminate)"
        c = interpreter.Context()
        try:
            while True:
                try:
                    s = raw_input("> ")
                except EOFError:
                    print
                    continue

                if s == "quit":
                    break
                
                for output in interpreter.evaluate(s, c):
                    print output
        except KeyboardInterrupt:
            pass
def _evaluate_attr(value, environ):
    """(get|set|del|has)attr

    (. obj attribute)           # getattr
    (.= obj attribute value)    # setattr
    (.? obj attribute)          # hasattr
    (del. obj attribute)        # delattr

    attribute - This is a Symbol.
    
    """
    from interpreter import evaluate # Circular dependency.
    function = value[0].name
    assert function in [".", ".=", ".?", "del."]
    if function == ".=":
        required_args = 4
        rval = evaluate(value[3], environ)
    else:
        required_args = 3
    if len(value) != required_args:
        raise SyntaxError("invalid syntax")
    obj, attribute = value[1], value[2]
    obj = evaluate(obj, environ)
    if not isinstance(attribute, Symbol):
        raise SyntaxError("attributes must be Symbol's")
    attribute = attribute.name
    if function == ".":
        return getattr(obj, attribute)
    if function == ".=":
        setattr(obj, attribute, rval)
        return rval
    if function == ".?":
        return hasattr(obj, attribute)
    if function == "del.":
        delattr(obj, attribute)
Exemple #5
0
    def test_calling_simple_function(self):
        """Test calling named function that's been previously defined 
        from the environment"""

        env = Environment()
        evaluate(["define", "my-fn", ["lambda", ["x"], "x"]], env)
        assert_equals(42, evaluate(["my-fn", 42], env))
Exemple #6
0
    def test_defining_then_looking_up_function(self):
        """Sanity check that we can hold and look up functions in the
        environment"""

        env = Environment()
        evaluate(["define", "my-fn", ["lambda", ["x"], "x"]], env)
        assert_equals("foo", env["my-fn"]("foo"))
Exemple #7
0
def interpret(args):
    with open(args.infile.name, args.infile.mode) as file:
        code = file.read()

    if args.non_encoded == False:
        code = encoder.decode(code.hex())
    else:
        code = cleanup(code.decode('cp1251'))

    arguments = {}

    if args.user_input != None:
        arguments["user_input"] = args.user_input

    if args.upper != None:
        arguments["upper"] = args.upper

    if args.lower != None:
        arguments["lower"] = args.lower

    if args.default != None:
        arguments["default"] = args.default

    if args.eof != None:
        arguments["eof"] = args.eof

    if args.non_wrapping == True:
        arguments["wrapping"] = False

    interpreter.evaluate(code, **arguments)
Exemple #8
0
 def test_defining_lambda_with_error(self):
     """Tests that the lambda body is not being evaluated when the lambda
     is evaluated or defined. (It should first be evaluated when the function
     is later invoced.)"""
 
     ast = parse("""
         (define fn-with-error
             (lambda (x y)
                 (function body that would never work)))
     """)
     evaluate(ast, Environment())
Exemple #9
0
def test_file_stuff():
    prog = dsl_parse("""
        (
            (defvar f _ (apply fopen 3))
            (scope
                (defvar fref _ (mkref f))
                (apply fwrite fref 33)
             )
             (apply fclose f)
        )
        """)
    evaluate(base_env(), prog)
Exemple #10
0
    def closure(environ, *args):
        """Apply the function to args, and return the results.
        
        Note, the function application should take place in a newly nested 
        Environ.  In this newly nested Environ, tie the formal arguments to
        the parameters using Expression's in order to implement lazy
        evaluation.  On the other hand, the parameter Expression's should be
        evaluated in the caller's Environ (i.e. (sum a b) should evaluate a and
        b in the caller's Environ, not sum's Environ).
        
        Return the last executed "statement" of the function.

        """
        from Environ import Environ # Circular dependency.
        from interpreter import evaluate # Circular dependency.
        if not len(parameters) == len(args):
            raise TypeError("%s() takes exactly %d arguments (%d given)" % 
                (name, len(parameters), len(args)))
        locals = Environ(parent = environ)
        for i in range(0, len(parameters)): 
            locals[parameters[i]] = Expression(environ = environ,
                parseTree = args[i])
        for i in body:
            ret = evaluate(i, locals)
        return ret
Exemple #11
0
    def __call__(self, implicitUnval=0, implicitLast=0):
        """Do lazy evaluation.
        
        Return value after having evaluated it.  Cache the evaluation so that
        subsequent calls don't cause additional evaluations (in case there
        are side effects).
        
        implicitUnval - During evaluation, if the Expression.parseTree is a 
        list, automatically treat the list as data (i.e. a call to the unval
        function) instead of a normal function call.  This is required in 
        certain situations such as the value (i.e. body) of an if statement,
        which are meant to feel like the body of a function definition.

        implicitLast - If after evaluation, the value is a list, return only
        the last element of that list.  Like implicitUnval, this is required in
        certain situations such as the value (i.e. body) of an if statement,
        which are meant to feel like the body of a function definition.

        """
        from interpreter import evaluate # Circular dependency.
        if isinstance(self.value, Expression):
            parseTree = self.value.parseTree
            if implicitUnval and isinstance(parseTree, type([])):
                parseTree.insert(0, Symbol(name = "'"))
            val = evaluate(parseTree, self.value.environ)
            if implicitLast and isinstance(val, type([])):
                val = val[-1]
            self.value = val
        return self.value
Exemple #12
0
def REPL():
    try:
        while True:
            code = input("-> ")
            print(evaluate(code))
    except KeyboardInterrupt:
        pass
Exemple #13
0
    def test_lambda_with_argument(self):
        """Test that the arguments are included in the environment when 
        the function body is evaluated"""

        ast = ["lambda", ["x"], "x"]
        fn = evaluate(ast, Environment())
        assert_equals("foo", fn("foo"))
Exemple #14
0
    def test_lambda_with_free_var(self):
        """Tests that the lambda have access to variables 
        from the environment in which it was defined"""

        ast = ["lambda", [], "free-variable"]
        fn = evaluate(ast, Environment({"free-variable": 100}))
        assert_equals(100, fn())
Exemple #15
0
def test_ref_fun():
    prog = dsl_parse(
        "((defvar x (un val int) 3)"
        "(defvar xref (un ref (un val int)) (mkref x)) "
        "(defun foo (un val int) ((y (un ref (un val int)))) (setrefval y (apply + (deref y) 1)))"
        "(apply foo xref)"
        "x)")
    assert evaluate(base_env(), prog) == 4
Exemple #16
0
def _test_evaluate_pyimport():
    from Environ import Environ # Circular dependency.
    from interpreter import evaluate # Circular dependency.
    pyimport = Symbol(name = "pyimport")
    locals = Environ()
    assert evaluate([pyimport, "sys"], locals) == sys
    assert locals.pythonGlobals["sys"] == sys
    assert locals.has_key("sys.version")
Exemple #17
0
def _test_evaluate_attr():
    from Environ import Environ # Circular dependency.
    from interpreter import evaluate # Circular dependency.
    locals = Environ()
    pyimport = Symbol(name = "pyimport")
    dot = Symbol(name = ".")
    dotEquals = Symbol(name = ".=")
    dotQuestion = Symbol(name = ".?")
    delDot = Symbol(name = "del.")
    UserList = Symbol(name = "UserList")
    foo = Symbol(name = "foo")
    evaluate([pyimport, "UserList"], locals)
    assert not evaluate([dotQuestion, UserList, foo], locals)
    evaluate([dotEquals, UserList, foo, 1], locals)
    assert evaluate([dot, UserList, foo], locals) == 1
    assert evaluate([dotQuestion, UserList, foo], locals)
    evaluate([delDot, UserList, foo], locals)
    assert not evaluate([dotQuestion, UserList, foo], locals)
    def closure(environ, *args):
        """Apply the function to args, and return the results.

        Because Python does not support lazy evaluation, the args must be 
        evaluated before passing them to the function.

        """
        from interpreter import evaluate # Circular dependency.
        parameters = [evaluate(i, environ) for i in args]
        return function(*parameters)
Exemple #19
0
    def test_calling_function_recursively(self):
        """Tests that a named function is included in the environment
        where it is evaluated"""

        # Starting env out with some "standard functions" this time
        import operator
        env = Environment({
            '-': operator.sub, 
            '>': operator.gt
        })
        
        # Meaningless (albeit recursive) function
        program = """
            (define fn 
                (lambda (x) 
                    (if (> x 0) 
                        (fn (- x 1))
                        1000)))
        """
        evaluate(parse(program), env)
        assert_equals(1000, evaluate(["fn", 10], env))
Exemple #20
0
def test_while_statement():
    prog = dsl_parse(
        "( (defvar x (un val foobar) 0) "
        "  (defvar y (un val foobar) 10) "
        "  (while (apply < x 10) -2 (  (set y (apply + y 1)) (set x (apply + x 1)) y)  ))"
    )
    assert evaluate(base_env(), prog) == 20

    prog = dsl_parse(
        "( (defvar x (un val foobar) 0) "
        "  (defvar y (un val foobar) 10) "
        "  (while (apply < x -4) -2 (  (set y (apply + y 1)) (set x (apply + x 1)) y)  ))"
    )
    assert evaluate(base_env(), prog) == -2

    prog = dsl_parse(
        "( (defvar x (un val foobar) 0) "
        "  (defvar y (un val foobar) 10) "
        "  (while (apply < x -4) -2 ((defvar z (un val foobar) 10) "
        "               (  (set y (apply + y 1)) (set x (apply + x 1)) y)  )) z)"
    )
    with pytest.raises(BindingUndefinedError):
        evaluate(base_env(), prog)

    prog = dsl_parse(
        "( (defvar x (un val foobar) 0) "
        "  (defvar y (un val foobar) 10) "
        "  (while (apply < x -4) -2 ((defvar z (un val foobar) 10) "
        "               ( (defvar 1 (un val foobar) 10) (set y (apply + y 1)) (set x (apply + x 1)) y)  )) q)"
    )
    with pytest.raises(BindingUndefinedError):
        evaluate(base_env(), prog)
Exemple #21
0
def test_recursive_fun():
    prog = dsl_parse(
        "("
        "(defun fib (un val int) ((n (un val int))) "
        "    (defvar ret (un val int) 0) "
        "    (if (apply = 0 n) (set ret 0) "
        "    (if (apply = 1 n) (set ret 1) "
        "            (set ret (apply +  (apply fib (apply - n 1))  (apply fib (apply - n 2))  ))))"
        "     ret"
        ")"
        "(apply fib 0))")
    assert evaluate(base_env(), prog) == 0

    prog = dsl_parse(
        "("
        "(defun fib (un val int) ((n (un val int))) "
        "    (defvar ret (un val int) 0) "
        "    (if (apply = 0 n) "
        "         (set ret 0) "
        "         (if (apply = 1 n) "
        "                 (set ret 1) "
        "                 (set ret (apply +  (apply fib (apply - n 1))  (apply fib (apply - n 2))  ))))"
        "     ret"
        ")"
        "(apply fib 2))")
    assert evaluate(base_env(), prog) == 1

    prog = dsl_parse(
        "("
        "(defun fib (un val int) ((n (un val int))) "
        "    (defvar ret (un val int) 0) "
        "    (if (apply = 0 n) "
        "         (set ret 0) "
        "         (if (apply = 1 n) "
        "                 (set ret 1) "
        "                 (set ret (apply +  (apply fib (apply - n 1))  (apply fib (apply - n 2))  ))))"
        "     ret"
        ")"
        "(apply fib 4))")
    assert evaluate(base_env(), prog) == 3
Exemple #22
0
    def test_begin_form(self):
        """Testing evaluating expressions in sequence with the begin 
        special form"""

        env = Environment()
        result = evaluate(parse("""
            (begin 
                (define foo 1)
                (define bar 2)
                foo)
        """), env)

        assert_equals(1, result)
        assert_equals(Environment({"foo": 1, "bar": 2}), env)
Exemple #23
0
 def mainLoop(self):
     """This is the main loop."""
     while 1:
         try:
             line = ""
             while not self.isComplete(line):
                 line += self.readline(line)
             value = evaluate(yacc.parse(line), self.environ)
             if self.isStdin and value:
                 print value
         except EOFError:
             self.input.close()
             break
         except:
             print_exception(*(sys.exc_info()))
Exemple #24
0
def _evaluate_pyimport(value, environ):
    """(pyimport name)
    
    Import the name module (name is anything that resolves to a string) into
    environ.pythonGlobals (if it hasn't already been imported) so that
    subsequent calls by environ to eval will be able to access it.
    environ.pythonGlobals is used instead of __main__ or __builtins__ for
    compatibility with Jython.  Return the module.
    
    """
    from interpreter import evaluate # Circular dependency.
    if len(value) != 2:
        raise SyntaxError("invalid syntax")
    name = evaluate(value[1], environ)
    if not isinstance(name, type("")):
        raise SyntaxError("'%s' is not a string" % name)
    if not environ.pythonGlobals.has_key(name):
        environ.pythonGlobals[name] = __import__(name)
    return environ.pythonGlobals[name]
Exemple #25
0
def test_if_statement():
    prog = dsl_parse("( if true 10 12 )")
    assert evaluate(base_env(), prog) == 10

    prog = dsl_parse(
        "(  (defvar x (un val foobar) 0) "
        "    (set x 1000)  "
        "    (defun add-3 (un val int) ((x (un val int))) (apply + x 3))"
        "    (if (apply = 3 3) (apply add-3 x) (apply add-3 (apply add-3 x)))"
        ")")
    assert evaluate(base_env(), prog) == 1003

    prog = dsl_parse(
        "(  (defvar x (un val foobar) 0) "
        "    (set x 1000)  "
        "    (defun add-3 (un val int) ((x (un val int))) (apply + x 3))"
        "    (if (apply = 3 4) (apply add-3 x) (apply add-3 (apply add-3 x)))"
        ")")
    assert evaluate(base_env(), prog) == 1006

    prog = dsl_parse(
        "(  (defvar x (lin val foobar) 0) "
        "    (set x 1000)  "
        "    (defun add-3 (un val int) ((x (un val int))) (apply + x 3))"
        "    (if (apply = 3 4) "
        "((defvar z (un val foobar) 10) (apply add-3 x)) "
        "(apply add-3 (apply add-3 z)))"
        ")")
    with pytest.raises(BindingUndefinedError):
        evaluate(base_env(), prog)

    prog = dsl_parse(
        "(  (defvar x (aff val foobar) 0) "
        "    (set x 1000)  "
        "    (defun add-3 (un val int) ((x (un val int))) (apply + x 3))"
        "    (if (apply = 3 4) "
        "(apply add-3 x) "
        "((defvar z (un val foobar) 10) (apply add-3 (apply add-3 z)))) z"
        ")")
    with pytest.raises(BindingUndefinedError):
        evaluate(base_env(), prog)
Exemple #26
0
 def _run(self, cls, instance, args, context, *, call):
     variables = {param: arg
                  for arg, (param, _) in zip(args, self.parameters)}
     generic_classes = dict(Generic.fill_generic(
         [pt for _, pt in self.parameters], [arg.type for arg in args]))
     scope = instance.scope
     description = self.description
     context = interpreter.Scope(description, scope,
                                 generic_classes, variables)
     context.stack.enter(interpreter.Frame(description, call))
     if cls.base:
         if self._super_arguments:
             arguments = [interpreter.evaluate(argument, scope)
                          for argument in self._super_arguments]
             cls.base.run_constructor(instance, arguments,
                                      context, call=call)
         else:
             cls.base.run_constructor(instance, (), scope, call=call)
     try:
         interpreter.execute(self._statements, context)
     except Return:
         pass
     scope.stack.exit()
Exemple #27
0
 def testEvaluateCompoundAddition2(self):
     symbols = [add, mul, 1, 2, 3]
     result = evaluate(symbols)
     self.assertEqual(result, 5)
Exemple #28
0
 def test_eval_boolean(self):
     assert_equals(True, evaluate(True, Environment()))
     assert_equals(False, evaluate(False, Environment()))
Exemple #29
0
def test_calling_functions():
    prog = dsl_parse("(apply + 3 4)")
    assert evaluate(base_env(), prog) == 7

    prog = dsl_parse("(apply <= 5 4)")
    assert evaluate(base_env(), prog) == False
Exemple #30
0
def test_ref():
    prog = dsl_parse("((defvar x (un val int) 3)"
                     "(defvar xref (un ref (un val int)) (mkref x)) "
                     "(setrefval xref (apply + (deref xref) 1))"
                     "x)")
    assert evaluate(base_env(), prog) == 4
Exemple #31
0
 def test_simple_if_statement(self):
     ast = ["if", True, 42, 1000]
     assert_equals(42, evaluate(ast, Environment()))
Exemple #32
0
def test_1():
    assert interpreter.evaluate('trim("Hello " "world" )') == 'Hello world'
Exemple #33
0
 def test_wrong_if_syntax(self):
     with assert_raises_regexp(LispSyntaxError, "Malformed if"):
         evaluate(["if", "with", "far", "too", "many", "parts"], Environment())
Exemple #34
0
 def test_adD(self):
     self.assertEqual(evaluate("(+ 1 (+ 1 (+ 1 1) 2) 3 (+ 2 2) 5)))"), 18)
Exemple #35
0
    def test_sqare(self):
        evaluate("(define (square x) (* x x) )")
        self.assertIn("square", operators.keys())

        self.assertEqual(evaluate("(square 2)"), 4)
Exemple #36
0
usage = '''

Ceres - A sequence-oriented recreational golfing language

ceres.py e <code> [arguments...] - Evaluate Ceres code from the third command line argument

ceres.py f <file> [arguments...] - Evaluate Ceres code from the contents of the file whose path is the third command line argument

'''

def unbool(array):
	if isinstance(array, list):
		return list(map(unbool, array))
	return 1. if array is True else 0. if array is False else array

def cut(array):
	if isinstance(array, list):
		return list(map(cut, array))
	return int(array) if isinstance(array, (int, float, complex)) and array % 1 == 0 else array

if __name__ == '__main__':
	if len(sys.argv) < 3 or sys.argv[1] not in 'ef': raise SystemExit(usage)
	if sys.argv[1] == 'e':
		code = sys.argv[2]
	else:
		code = open(sys.argv[2]).read()
	arguments = list(map(interpreter.floatify, map(eval, sys.argv[3:])))
	result = interpreter.evaluate(code, arguments)
	if result: print(cut(unbool(result.pop())))
Exemple #37
0
yacc.yacc(debug=1)

if __name__ == '__main__':
    from optparse import OptionParser
    parser = OptionParser()
    (options, args) = parser.parse_args()
    if len(args) > 0:
        context = RootGameContext()
        # run file
        for filename in args:
            print "opening file: " + filename
            with open(filename) as jang_file:
                statements = yacc.parse(jang_file.read())
                for statement in statements:
                    interpreter.evaluate(statement, context)
    else:
        # REPL
        import cPickle as pickle
        context = RootGameContext()
        while True:
            try:
                s = raw_input('> ')
            except EOFError:
                break
            try:
                statements = yacc.parse(s)
                for statement in statements:
                    evaluated = interpreter.evaluate(statement, context)
                    # print pickle.dumps(context)
                if evaluated is not None:
Exemple #38
0
 def test_wrong_define_syntax(self):
     with assert_raises_regexp(LispSyntaxError, "Malformed define"):
         evaluate(["define", "x"], Environment())
Exemple #39
0
import argparse
import interpreter
import sys

version = '0.0.3'
debug = False


def parse_args():
    parser = argparse.ArgumentParser()
    parser = argparse.ArgumentParser(
        description='Official Proxima Language Interpreter.')
    parser.add_argument('file', nargs='?')
    return parser.parse_args()


if __name__ == '__main__':
    args = parse_args()

    if not debug:
        sys.tracebacklimit = 0

    if args.file:
        with open(args.file) as f:
            interpreter.evaluate(f.read())
Exemple #40
0
    def test_calling_lambda_directly(self):
        """Tests that it's is possible to define a lambda function and
        then calling it directly"""

        assert_equals(42, evaluate([["lambda", ["x"], "x"], 42], Environment()))
Exemple #41
0
 def testEvaluateCompoundOperations(self):
     symbols = [add, 1, mul, 2, 3]
     result = evaluate(symbols)
     self.assertEqual(result, 7)
Exemple #42
0
 def test_complex(self):
     evaluate("(define (f x) (* x x (+ 5 x) ) )")
     self.assertIn("f", operators.keys())
     self.assertEqual(evaluate("(f 2)"), 28)
Exemple #43
0
 def test_lambda_with_no_free_vars(self):
     "Tests that the lambda executes it's body when called"
     
     ast = ["lambda", [], 42]
     fn = evaluate(ast, Environment())
     assert_equals(42, fn())
Exemple #44
0
 def test_let(self):
     #print operate(findInnerMost(listify ("( + x u )")))
     self.assertEqual(evaluate("(let ((x 2) (u 50)) (+ x u)"), 52)
Exemple #45
0
 def test_define(self):
     ast = ["define", "x", 1000]
     env = Environment()
     evaluate(ast, env)
     assert_equals(1000, env["x"])
Exemple #46
0
def test_2():
    assert interpreter.evaluate(
        'nws({Много пробелов это   плохо})  ') == 'Много пробелов это плохо'
Exemple #47
0
def test_seq_eval():
    prog = dsl_parse("(true 3)")
    assert evaluate(base_env(), prog) == 3
Exemple #48
0
def test_3():
    assert interpreter.evaluate(
        'seq  (/Winter Olympics/, <Winter Olympics>)') == '1'
Exemple #49
0
 def test_if_with_variable_lookup(self):
     ast = ["if", "pred", "then", "else"]
     env = Environment({"pred": False, "else": 42})
     assert_equals(42, evaluate(ast, env))
Exemple #50
0
def test_4():
    assert interpreter.evaluate(
        'trim("  "):-/Unknown value/') == 'Unknown value'
Exemple #51
0
def test_define_variable():
    prog = dsl_parse("(defvar x (un val footype) 3)")
    assert evaluate(base_env(), prog) is None

    prog = dsl_parse("((defvar x (un val footype) 3) x)")
    assert evaluate(base_env(), prog) == 3
Exemple #52
0
def test_5():
    assert interpreter.evaluate('trim(/  /):+add(2, 2)') == '4'
Exemple #53
0
def test_var_access():
    prog = dsl_parse("( (defvar x (lin val footype) 0) (set x 3)  x )")
    assert evaluate(base_env(), prog) == 3

    prog = dsl_parse("( (defvar x (aff val footype) 0) (set x 4) (set x 3) 3)")
    assert evaluate(base_env(), prog) == 3
Exemple #54
0
def test_6():
    assert interpreter.evaluate('trim([ Privet]):+add(2, 2)') == 'Privet'
Exemple #55
0
 def test_eval_integer(self):
     assert_equals(42, evaluate(42, Environment()))
Exemple #56
0
def test_7():
    assert interpreter.evaluate('bomb()') == interpreter.BOMB
Exemple #57
0
            raise TypeError("%s() takes exactly %d arguments (%d given)" % 
                (name, len(parameters), len(args)))
        locals = Environ(parent = environ)
        for i in range(0, len(parameters)): 
            locals[parameters[i]] = Expression(environ = environ,
                parseTree = args[i])
        for i in body:
            ret = evaluate(i, locals)
        return ret

    closure.lazy = 1
    return closure


# Do some testing.
if __name__ == '__main__':
    from Environ import Environ # Circular dependency.
    from interpreter import evaluate # Circular dependency.
    locals = Environ()
    def_ = Symbol(name = "def")
    foo = Symbol(name = "foo")
    _ = Symbol(name = "_")
    arg1 = Symbol(name = "arg1")
    arg2 = Symbol(name = "arg2")
    div_ = Symbol(name = "/")
    f = evaluate([def_, foo, [arg1, arg2], arg1], locals)
    assert hasattr(f, "lazy")
    assert evaluate([foo, "spam", [div_, 1, 0]], locals) == "spam"
    assert evaluate([f, "spam", [div_, 1, 0]], locals) == "spam"
    assert not locals.has_key(arg1.name)
Exemple #58
0
def test_0():
    assert interpreter.evaluate(' add ( r(1.33, 0.25, "up"), neg(1))') == '0.5'
Exemple #59
0
    """

    def closure(environ, *args):
        """Apply the function to args, and return the results.

        Wrap each argument in a Parameter instance before applying the 
        function.  Please see Parameter.py and builtins.py.

        """
        parameters = []
        for i in args:
            expression = Expression(environ = environ, parseTree = i)
            parameter = Parameter(value = expression)
            parameters.append(parameter)
        return function(*parameters)

    closure.lazy = 1
    return closure


# Do some testing.
if __name__ == '__main__':
    from Environ import Environ # Circular dependency.
    from interpreter import evaluate # Circular dependency.
    locals = Environ()
    def builtin_add(a, b): return a() + b()
    locals["+"] = create_builtin_function("+", builtin_add)
    assert hasattr(locals["+"], "lazy")
    plus = Symbol(name = "+")
    assert evaluate([plus, 1, [plus, 1, 1]], locals) == 3
Exemple #60
0
 def test_simple_lookup_from_env(self):
     env = Environment({"foo": 42, "bar": True})
     assert_equals(42, evaluate("foo", env))