コード例 #1
0
def test_calling_atom_raises_exception():
    """A function call to a non-function should result in an error."""

    with assert_raises_regexp(LispError, "not a function"):
        evaluate(parse("(#t 'foo 'bar)"), Environment())
    with assert_raises_regexp(LispError, "not a function"):
        evaluate(parse("(42)"), Environment())
コード例 #2
0
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())
コード例 #3
0
def test_parse_exception_extra_paren():
    """Another exception is raised if the expression is too large.

    The parse function expects to receive only one single expression. Anything
    more than this, should result in the proper exception."""

    with assert_raises_regexp(LispError, 'Expected EOF'):
        parse('(foo (bar x y)))')
コード例 #4
0
def test_parse_boolean():
    """Parsing single booleans.

    Booleans are the special symbols #t and #f. In the ASTs they are represented
    by Pythons True and False, respectively. """

    assert_equals(True, parse('#t'))
    assert_equals(False, parse('#f'))
コード例 #5
0
def test_calling_with_wrong_number_of_arguments():
    """Functions should raise exceptions when called with wrong number of arguments."""

    env = Environment()
    evaluate(parse("(define fn (lambda (p1 p2) 'whatever))"), env)
    error_msg = "wrong number of arguments, expected 2 got 3"
    with assert_raises_regexp(LispError, error_msg):
        evaluate(parse("(fn 1 2 3)"), env)
コード例 #6
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()))
コード例 #7
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)
コード例 #8
0
def test_parse_integer():
    """Parsing single integer.

    Integers are represented in the ASTs as Python ints.

    Tip: String objects have a handy .isdigit() method.
    """

    assert_equals(42, parse('42'))
    assert_equals(1337, parse('1337'))
コード例 #9
0
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 #f 0 (+ 10 10))")]

    assert_equals(25, evaluate(ast, env))
コード例 #10
0
def test_math_operators_only_work_on_numbers():
    """The math functions should only allow numbers as arguments."""

    with assert_raises(LispError):
        evaluate(parse("(+ 1 'foo)"), Environment())
    with assert_raises(LispError):
        evaluate(parse("(- 1 'foo)"), Environment())
    with assert_raises(LispError):
        evaluate(parse("(/ 1 'foo)"), Environment())
    with assert_raises(LispError):
        evaluate(parse("(mod 1 'foo)"), Environment())
コード例 #11
0
def test_parse_list_of_symbols():
    """Parsing list of only symbols.

    A list is represented by a number of elements surrounded by parens. Python lists
    are used to represent lists as ASTs.

    Tip: The useful helper function `find_matching_paren` is already provided in
    `parse.py`.
    """

    assert_equals(['foo', 'bar', 'baz'], parse('(foo bar baz)'))
    assert_equals([], parse('()'))
コード例 #12
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(parse("(1 2 3 #t)"),
                  evaluate(parse("'(1 2 3 #t)"), Environment()))
コード例 #13
0
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("(define 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)
コード例 #14
0
def test_basic_if_statement():
    """If statements are the basic control structures.

    The `if` should first evaluate its 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 #t 42 1000)")
    assert_equals(42, evaluate(if_expression, Environment()))
    if_expression = parse("(if #f 42 1000)")
    assert_equals(1000, evaluate(if_expression, Environment()))
    if_expression = parse("(if #t #t #f)")
    assert_equals(True, evaluate(if_expression, Environment()))
コード例 #15
0
    def test_parsing(self):
        raw_price = '1 295,00 SEK'
        parse_type = 'zara'

        parsed_price = parser.parse(parse_type, raw_price)

        assert parsed_price == '1295'
コード例 #16
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()))

    # From this point, the ASTs might sometimes be too long or cummbersome to
    # write down explicitly, and we'll use `parse` to make them for us.
    # Remember, if you need to have a look at exactly what is passed to `evaluate`,
    # just add a print statement in the test (or in `evaluate`).

    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()))
コード例 #17
0
 def test_assignment(self):
     string = "test = a;"
     parseRes = parse(string)
     self.assertEquals(
         parseRes,
         ["statements", [["assign", ["usage", "test"], ["usage", "a"]]]])
     pass
コード例 #18
0
ファイル: asm.py プロジェクト: m-wichmann/pyArch
def pyArch_asm_main():

    parser = argparse.ArgumentParser()
    parser.add_argument("-i",
                        "--infile",
                        action="store",
                        dest="infile",
                        help="infile")
    parser.add_argument("-o",
                        "--outfile",
                        action="store",
                        dest="outfile",
                        help="outfile")
    args = parser.parse_args()

    infile = 'test.s'
    outfile = 'test.out'

    if args.infile:
        infile = args.infile
    if args.outfile:
        outfile = args.outfile

    tokenizer = src.token.Tokenizer()
    parser = src.parser.Parser()
    output = src.output.Output()

    lines = read_file(infile)
    tokens = tokenizer.tokenize(lines)
    parsed_tokens = parser.parse(tokens)
    output.output_text(parsed_tokens, outfile)
コード例 #19
0
    def instrument(self, contract_path, contract_name, predicates, **kargs):
        instrument_for_echidna = kargs.get('for_echidna', False)
        reuse_pre_process = kargs.get('reuse_pre_process', False)

        if reuse_pre_process:
            self.contract_path = contract_path
        else:
            self.pre_process_contract(contract_path, contract_name)

        with open(self.contract_path) as contract_file:
            self.contract_lines = contract_file.readlines()

        parser = Parser()

        for index, predicate_string in enumerate(predicates):
            predicate = parser.parse(predicate_string)

            functions_to_instrument = self.__get_functions_to_instrument(predicate)

            self.__instrument_new_variables(predicate, functions_to_instrument, instrument_for_echidna)

            if instrument_for_echidna:
                echidna_function = f'function echidna_VERIMAN_predicate_no_{str(index + 1)}() public returns(bool){{\nreturn {predicate.solidity_repr};\n}}'
                self.__insert_in_contract(echidna_function)
            else:
                assert_string = f'assert({predicate.solidity_repr}); // VERIMAN ASSERT FOR PREDICATE NO. {index + 1}'
                self.__insert_at_functions_end(functions_to_instrument, assert_string)

        with open(self.contract_path, 'w') as contract_file:
            contract_file.writelines(self.contract_lines)
コード例 #20
0
def test_parse_single_symbol():
    """Parsing a single symbol.

    Symbols are represented by text strings. Parsing a single atom should result
    in an AST consisting of only that symbol."""

    assert_equals('foo', parse('foo'))
コード例 #21
0
ファイル: main.py プロジェクト: Tarrasch/ravens-test
def main():
  problems = ['2-1', '2-2', '2-3', '2-4', '2-5', '2-6', '2-7', '2-8',
              '3-7', '3-8',
              '4-7', '4-8']
  for x in problems:
    file_path = "reps/%s" % x
    if os.path.exists(file_path):
      image_tree = parse(file_path)
      d = meta(image_tree)
      print "============================================================"
      print "The most likely answer based on both solvers is: \t%s" % d['ans']
      print ""
      print "Motivation: " + d['motivation']
      print ""
      if show_both:
        print "--------------------------------------------------------"
        print "Visual solution to problem %s is:" % (x)
        pprint(d['vis'][verbosity])
        print ""
        print "--------------------------------------------------------"
        print "Solution to problem %s is:" % (x)
        pprint(d['rep'][verbosity])
      else:
        print "The used (%s) solver gave this answer/solution:" % d['used']
        pprint(d[d['used']][verbosity])
      print "============================================================"

      print "\n\n\n"
    else:
      print "Didn't find representation for file %s" % x
コード例 #22
0
ファイル: app.py プロジェクト: DuhastMish/Computer_Network
    def __init__(self, input_model: str = '2d'):
        self.log_list = []
        pygame.init()
        self.input_model = input_model
        config = parse(input_model)

        self.periscope: Periscope = Periscope(config)
        p_target = self.periscope.ray_to_aim().intersect_plane(
            Triangle(Point3d(0.2, 0.5, 0.2),
                     Point3d(0.2, 0.4, 0.1),
                     Point3d(0.2, 0.3, 0.5)
                     ))
        tee = Target(p_target, config["target_radius"])
        self.periscope.set_target(tee)

        self.renderer = Renderer(self.periscope)

        # Shared memory
        self.down_plane_points = mp.Array('d', 6)
        self.up_plane_points = mp.Array('d', 6)
        self.__init_share_memory()

        self.up_plane_queue = mp.Queue()
        self.down_plane_queue = mp.Queue()

        self.up_plane_process: mp.Process = mp.Process(
            target=DirectAlgorithm.plane_direct_process,
            args=(self.up_plane_queue, self.up_plane_points, self.periscope, MirrorLocation.UP))
        self.down_plane_process: mp.Process = mp.Process(
            target=DirectAlgorithm.plane_direct_process,
            args=(self.down_plane_queue, self.down_plane_points, self.periscope, MirrorLocation.DOWN))
コード例 #23
0
    def test_bigFunctionDef(self):
        string = '''
        (a, b, c) -> 
            a = a + 1;
            b = b + a;
        done;'''
        parser = parse(string)

        self.assertEquals([
            'statements',
            [[
                'func',
                ['params', [['param', 'c'], ['param', 'b'], ['param', 'a']]],
                [
                    'block',
                    [[
                        'assign', ['usage', 'a'],
                        ['binop', ['usage', 'a'], '+', ['int', '1']]
                    ],
                     [
                         'assign', ['usage', 'b'],
                         ['binop', ['usage', 'b'], '+', ['usage', 'a']]
                     ]]
                ]
            ]]
        ], parser)
        pass
コード例 #24
0
def main(arg_list):
    args = get_args(arg_list)
    if args.subparser == "world":
        level, signs = parser.load_level_from_world(args.world, \
                (np.array(args.start), np.array(args.end)))
        l = parser.parse(level, signs)
    elif args.subparser == "npy":
        level, signs = parser.load_level_from_npy(args.level_file,
                                                  args.sign_file)
        l = parser.parse(level, signs)
    elif args.subparser == "convert":
        level, signs = parser.load_level_from_world(args.world, \
                (np.array(args.start), np.array(args.end)))
        parser.save_level(level, signs, args.level_file, args.sign_file)
    else:
        assert False, "Bad subparser: {}".format(args.subparser)
コード例 #25
0
ファイル: TestParser.py プロジェクト: radding/Arbor
 def test_return(self):
     string = "return a + b;"
     parser = parse(string, True)
     self.assertEquals([
         'statements',
         [['return', ['binop', ['usage', 'a'], '+', ['usage', 'b']]]]
     ], parser)
コード例 #26
0
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)
コード例 #27
0
    def __init__(self, conf: str):
        self.conf = conf
        config = parse(conf)
        self.periscope: Periscope = Periscope(config)

        p_target = self.periscope.ray_to_aim().intersect_plane(
            Triangle(Point3d(0.2, 0.5, 0.2), Point3d(0.2, 0.4, 0.1),
                     Point3d(0.2, 0.3, 0.5)))
        tee = Target(p_target, 0.02)
        self.periscope.set_target(tee)

        plane_up = self.periscope.mirror_up.triangle
        plane_down = self.periscope.mirror_down.triangle
        self.down_plane = Triangle(plane_down.point_a, plane_down.point_b,
                                   plane_down.point_c)
        self.up_plane = Triangle(plane_up.point_a, plane_up.point_b,
                                 plane_up.point_c)

        self.base_length = {
            'up': Vector(plane_up.point_c, plane_up.point_b).length(),
            'down': Vector(plane_down.point_c, plane_down.point_b).length()
        }
        self.height_length = {
            'up':
            Vector(plane_up.point_a,
                   (plane_up.point_b + plane_up.point_c) / 2).length(),
            'down':
            Vector(plane_down.point_a,
                   (plane_down.point_b + plane_down.point_c) / 2).length()
        }

        self.side_length = {
            'up': Vector(plane_up.point_a, plane_up.point_b).length(),
            'down': Vector(plane_down.point_a, plane_down.point_b).length()
        }
コード例 #28
0
ファイル: TestParser.py プロジェクト: radding/Arbor
    def test_bigFunctionDefWithType(self):
        string = '''
        (a:int, b:float, c:char, d:function) -> 
            a = a + 1;
            b = b + a;
        done;'''
        parser = parse(string, True)

        self.assertEquals([
            'statements',
            [[
                'func',
                [
                    'params',
                    [['paramtype', 'd', 'function'], [
                        'paramtype', 'c', 'char'
                    ], ['paramtype', 'b', 'float'], ['paramtype', 'a', 'int']]
                ],
                [
                    'block',
                    [[
                        'assign', ['usage', 'a'],
                        ['binop', ['usage', 'a'], '+', ['int', '1']]
                    ],
                     [
                         'assign', ['usage', 'b'],
                         ['binop', ['usage', 'b'], '+', ['usage', 'a']]
                     ]]
                ]
            ]]
        ], parser)
        pass
コード例 #29
0
def test_calling_function_recursively():
    """Tests that a named function is included in the environment
    where it is evaluated."""

    env = Environment()
    evaluate(parse("""
        (define 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))
コード例 #30
0
    def test_functionNoParams(self):
        string = '''
        () -> 
            a = a + 1;
            b = b + a;
        done;'''
        parser = parse(string)

        self.assertEquals([
            'statements',
            [[
                'func', None,
                [
                    'block',
                    [[
                        'assign', ['usage', 'a'],
                        ['binop', ['usage', 'a'], '+', ['int', '1']]
                    ],
                     [
                         'assign', ['usage', 'b'],
                         ['binop', ['usage', 'b'], '+', ['usage', 'a']]
                     ]]
                ]
            ]]
        ], parser)
        pass
コード例 #31
0
def get_element_value(url, css_selector, parse_type):
    try:
        browser = webdriver.PhantomJS()
        # Wait for response for 30 seconds before timing out
        browser.implicitly_wait(30)

        logger.info('Requesting [%s]', url)
        browser.get(url)

        if browser.page_source == RESPONSE_404:
            msg = 'Request came back with status code 404'
            logger.error(msg)
            raise BadResponseException(msg)

        logger.info('Request came back with status code 200, all is good')

        logger.info('Querying response with selector=[%s]', css_selector)
        html_value_ele = browser.find_element_by_css_selector(css_selector)

        raw_value = html_value_ele.text
        logger.info('Found value=[%s]', raw_value)

        # raw_value = '1 295,00 SEK'  # Testing Zara

        parsed_value = parser.parse(parse_type, raw_value)
        logger.info('Parsed value to=[%s]', parsed_value)

        return parsed_value

    except NoSuchElementException as e:
        logger.error(
            'The CSS selector did not find anything on the URL, '
            'selector=[%s] URL=[%s]', css_selector, url)
        raise e
コード例 #32
0
def main(args_str):
    args = add_arguments(args_str)

    for file in args.files:
        if len(args.files) > 1:
            print(file.name + ':', end=' ')
        try:
            parse(file.read())
            print('Correct')
        except IllegalCharacter as e:
            print('IllegalCharacter: \'{}\', line {}'.format(e.value, e.line))
        except IncompleteToken as e:
            print('IncompleteToken:', e.value)

    for file in args.files:
        file.close()
コード例 #33
0
ファイル: main.py プロジェクト: Tarrasch/ravens-test
def main():
    problems = [
        '2-1', '2-2', '2-3', '2-4', '2-5', '2-6', '2-7', '2-8', '3-7', '3-8',
        '4-7', '4-8'
    ]
    for x in problems:
        file_path = "reps/%s" % x
        if os.path.exists(file_path):
            image_tree = parse(file_path)
            d = meta(image_tree)
            print "============================================================"
            print "The most likely answer based on both solvers is: \t%s" % d[
                'ans']
            print ""
            print "Motivation: " + d['motivation']
            print ""
            if show_both:
                print "--------------------------------------------------------"
                print "Visual solution to problem %s is:" % (x)
                pprint(d['vis'][verbosity])
                print ""
                print "--------------------------------------------------------"
                print "Solution to problem %s is:" % (x)
                pprint(d['rep'][verbosity])
            else:
                print "The used (%s) solver gave this answer/solution:" % d[
                    'used']
                pprint(d[d['used']][verbosity])
            print "============================================================"

            print "\n\n\n"
        else:
            print "Didn't find representation for file %s" % x
コード例 #34
0
def test_parse_list_of_mixed_types():
    """Parsing a list containing different types.

    When parsing lists, make sure each of the sub-expressions are also parsed
    properly."""

    assert_equals(['foo', True, 123], parse('(foo #t 123)'))
コード例 #35
0
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)
コード例 #36
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("(define foo (+ 2 2))"), env)
    assert_equals(4, evaluate("foo", env))
コード例 #37
0
ファイル: TestParser.py プロジェクト: radding/Arbor
    def test_booleanOps(self):
        string = "a && b;"
        parser = parse(string, True)
        self.assertEquals(
            ["statements", [["bool", ["usage", "a"], "&&", ["usage", "b"]]]],
            parser)

        string = "a || b;"
        parser = parse(string, True)
        self.assertEquals(
            ['statements', [['bool', ['usage', 'a'], '||', ['usage', 'b']]]],
            parser)

        string = "!a;"
        parser = parse(string, True)
        self.assertEquals(['statements', [['not', ['usage', 'a']]]], parser)
        pass
コード例 #38
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()))

    # From this point, the ASTs might sometimes be too long or cummbersome to
    # write down explicitly, and we'll use `parse` to make them for us.
    # Remember, if you need to have a look at exactly what is passed to `evaluate`,
    # just add a print statement in the test (or in `evaluate`).

    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()))
コード例 #39
0
def test_parse_on_nested_list():
    """Parsing should also handle nested lists properly."""

    program = '(foo (bar ((#t)) x) (baz y))'
    ast = ['foo',
           ['bar', [[True]], 'x'],
           ['baz', 'y']]
    assert_equals(ast, parse(program))
コード例 #40
0
def test_calling_function_recursively():
    """Tests that a named function is included in the environment
    where it is evaluated."""

    env = Environment()
    evaluate(
        parse("""
        (define 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))
コード例 #41
0
ファイル: test_parser.py プロジェクト: cmgn/dog
def test_parse_trivial_tokens():
    tests = (
        ((TokenType.INTEGER, "5"), 5),
        ((TokenType.SYMBOL, "abc"), "abc"),
        ((TokenType.FLOAT, "5.0"), 5.0),
    )
    for given, expected in tests:
        assert parse([given]) == [expected]
コード例 #42
0
 def test_array_def(self):
     for typet, size, name in product(
             ['int', 'float'],
             [8, 100, 0],
             ['bla', 'arrayname']):
         ast = parser.parse(
             """%s %s [%s];""" % (typet, name, size))
         self.assertEqual(type(ast), parser.ArrayDef)
         self.assertEqual(ast.name, name)
         self.assertEqual(ast.type, typet)
         self.assertEqual(ast.size, parser.Literal('int', size))
     # dynamic size
     ast = parser.parse("float arr[2*a];")
     self.assertEqual(type(ast), parser.ArrayDef)
     self.assertEqual(ast.name, 'arr')
     self.assertEqual(ast.type, typet)
     self.assertEqual(ast.size, parser.BinOp('*', parser.Literal('int', 2), parser.Variable('a')))
コード例 #43
0
 def test_compound(self):
     ast = parser.parse("""{
         int x;
         while(1 == 2) {
             5+4*8.0;
         }
         2.9;
     }""")
     self.checkComp(ast, parser.DeclStmt, parser.WhileStmt, parser.Literal)
コード例 #44
0
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)
コード例 #45
0
 def js_innerHTML(self, handle, s):
     doc = parse(lex("<html><body>" + s + "</body></html>"))
     new_nodes = doc.children[0].children
     elt = self.handle_to_node[handle]
     elt.children = new_nodes
     for child in elt.children:
         child.parent = elt
     print("Layout called from js_innerHTML")
     self.reflow(layout_for_node(self.document, elt))
コード例 #46
0
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)
コード例 #47
0
def upload_data(contents, option_ok, option_cancel, sheet_index):
    """Docstring."""
    datasets, modal, alert, url = dash.no_update, dash.no_update, dash.no_update, dash.no_update

    ctx = dash.callback_context

    if contents:
        #content_type, content = contents.split(',')

        if ctx.triggered[0]['prop_id'] == 'upload-data.contents':

            if contents.split(',')[0] in settings.FILETYPE['spreadsheet']:
                modal = True

            elif contents.split(',')[0] in settings.FILETYPE['csv']:
                status, datasets = parser.parse(contents.split(',')[1], 'csv')

            else:
                alert = dbc.Alert(['Non supported file type'],
                                  dismissable=True,
                                  color='danger')

        elif ctx.triggered[0]['prop_id'] == 'upload-option-ok.n_clicks':

            status, datasets = parser.parse(
                contents.split(',')[1], 'spreadsheet', sheet_index)

            if status == 'wrong_sheet_index':
                alert = dbc.Alert(['Sheet Index not found'],
                                  dismissable=True,
                                  color='danger')
            else:
                pass
            modal = False

        elif ctx.triggered[0]['prop_id'] == 'upload-option-cancel.n_clicks':
            modal = False

    if isinstance(datasets, dict):
        df = pd.read_json(datasets['data'], orient='split')
        url = '/data_preview'
        datasets = json.dumps(datasets)

    return datasets, modal, alert, url
コード例 #48
0
 def test_while(self):
     ast = parser.parse(
         """while(1) {
             int x = 2;
         }""")
     self.assertEqual(type(ast), parser.WhileStmt)
     self.assertEqual(type(ast.expression), parser.Literal)
     self.assertEqual(ast.expression.type, 'int')
     self.assertEqual(ast.expression.val, 1)
     self.checkComp(ast.stmt, parser.DeclStmt)
コード例 #49
0
def test_parse_with_extra_whitespace():
    """Excess whitespace should be removed."""

    program = """

       (program    with   much        whitespace)
    """

    expected_ast = ['program', 'with', 'much', 'whitespace']
    assert_equals(expected_ast, parse(program))
コード例 #50
0
def execute(expr, env=None):
    if env == None:
        env = defaultenv()
    lexer = Lexer(expr)
    parsetree = parse(lexer)
    try:
        result = present(evaluate(parsetree, env))
        return result
    except BaseException as exc:
        return str(exc)
コード例 #51
0
def run_test(testfile):
    with open(testfile, "r") as fp:
        data = fp.read()
    function_name, *tests = [x.strip() for x in data.split("===\n")]
    printf("Running fragment test for function '{}'\n{}", function_name, "=" * 60)
    func = getattr(parser, function_name)
    for test in tests:
        ast = parser.parse(test, func)
        print(ast)
    print("")
コード例 #52
0
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()))
コード例 #53
0
 def test_if(self):
     string = '''
     if (a) ->
         a;
     done;
     '''
     parser = parse(string, True)
     self.assertEquals(
         ['statements', [['if', ['usage', 'a'], [['usage', 'a']]]]], parser)
     pass
コード例 #54
0
def test_expand_single_quoted_symbol():
    """Quoting is a shorthand syntax for calling the `quote` form.

    Examples:

        'foo -> (quote foo)
        '(foo bar) -> (quote (foo bar))

    """
    assert_equals(["foo", ["quote", "nil"]], parse("(foo 'nil)"))
コード例 #55
0
ファイル: main.py プロジェクト: zjl233/moe
def test_prog():
    prog = '''
    var y = 10;
    var x = 20;
    print(x + y);
    '''
    tokens = lex(prog)
    # print(list(tokens))
    tree = parse(tokens)
    print(type(tree))
    tree.eval({})
コード例 #56
0
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)
コード例 #57
0
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)
コード例 #58
0
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)