Beispiel #1
0
 def test_while(self):
     self.stmt(ast.While(ast.Num(3), [], []), "empty body on While")
     self.stmt(ast.While(ast.Name("x", ast.Store()), [ast.Pass()], []),
               "must have Load context")
     self.stmt(ast.While(ast.Num(3), [ast.Pass()],
                          [ast.Expr(ast.Name("x", ast.Store()))]),
                          "must have Load context")
Beispiel #2
0
 def test_While(self):
     got = ast.While(None, self.simple_stmt(), self.simple_stmt())
     want = ast.While(None, self.simple_stmt(), [])
     self.check_transform(got, want)
     got = ast.While(None, self.fancy_stmts(), self.fancy_stmts())
     want = ast.While(None, [self.func], [self.func])
     self.check_transform(got, want)
Beispiel #3
0
 def test_empty_While(self):
     while_ = ast.While(ast.Num(42), [], [])
     self._test_empty_body(while_)
     # An empty 'else' clause should be eliminated.
     while_else = ast.While(ast.Num(42), [ast.Pass()],
                            [ast.Pass()])
     expect = ast.While(ast.Num(42), [ast.Pass()], [])
     self.check_transform(while_else, expect)
Beispiel #4
0
 def p_stmt_while(self, p):
     'stmt : WHILE expr DO stmt_list END'
     p[0] = ast.While(test=p[2],
                      body=p[4],
                      orelse=[],
                      lineno=p.lineno(1),
                      col_offset=p.lexpos(1))
Beispiel #5
0
    def visit_FunctionDef(self, node):
        self.generic_visit(node)
        if (self.__depth == 2) and (node.name in self.__to_inject_init):
            # 注入变量
            code_init = '\n'.join(self.__to_inject_init[node.name])
            location_patcher = LocationPatcher(node)
            code_init_ast = location_patcher.visit(ast.parse(code_init))
            code_loop = '\n'.join(
                self.__to_inject_loop[node.name])  # 每个信号或函数注入的语句可能都相同
            code_loop_ast = location_patcher.visit(ast.parse(code_loop))
            barnum_ast = location_patcher.visit(
                ast.parse('BarNum = get_current_bar()'))

            while_node = ast.copy_location(
                ast.While(
                    body=barnum_ast.body + code_loop_ast.body + node.body,
                    test=ast.copy_location(ast.NameConstant(value=True), node),
                    orelse=[]), node)
            self.return_to_yield(while_node)
            node.body = code_init_ast.body + [while_node]
            # 改变函数签名
            node.args.kwonlyargs.append(
                location_patcher.visit(
                    ast.arg(arg='series_id', annotation=None)))
            node.args.kw_defaults.append(location_patcher.visit(ast.Str(s='')))
Beispiel #6
0
def isl2py_for(n):
    assert n.get_type() == isl.ast_node_type.for_
    for_var = n.for_get_iterator()
    assert for_var.get_type() == isl.ast_expr_type.id
    for_var_name = for_var.get_id().name

    # Initialize loop variable
    py_asign = pyast.Assign(
        targets=[pyast.Name(for_var_name, pyast.Store())],
        value=isl2py_exp(n.for_get_init()),
    )

    # Increment statement
    py_inc = pyast.AugAssign(
        target=pyast.Name(for_var_name, pyast.Store()),
        op=pyast.Add(),
        value=isl2py_exp(n.for_get_inc()),
    )

    # python loop body
    py_body = isl2py_ast(n.for_get_body()) + [py_inc]

    ret = [
        py_asign,
        pyast.While(test=isl2py_exp(n.for_get_cond()), body=py_body, orelse=[]),
    ]

    return ret
Beispiel #7
0
def astForCFor(funcEnv, stmnt):
    assert isinstance(stmnt, CForStatement)
    assert len(stmnt.args) == 3
    assert isinstance(
        stmnt.args[1], CStatement
    )  # second arg is the check; we must be able to evaluate that

    # introduce dummy 'if' AST so that we have a scope for the for-loop (esp. the first statement)
    ifAst = ast.If(body=[],
                   orelse=[],
                   test=ast.Name(id="True", ctx=ast.Load()))
    funcEnv.pushScope(ifAst.body)
    cStatementToPyAst(funcEnv, stmnt.args[0])

    whileAst = ast.While(body=[],
                         orelse=[],
                         test=ast.Name(id="True", ctx=ast.Load()))
    ifAst.body.append(whileAst)

    ifTestAst = ast.If(body=[ast.Pass()], orelse=[ast.Break()])
    ifTestAst.test = getAstNode_valueFromObj(
        funcEnv.globalScope.stateStruct,
        *astAndTypeForCStatement(funcEnv, stmnt.args[1]))
    whileAst.body.append(ifTestAst)

    funcEnv.pushScope(whileAst.body)
    if stmnt.body is not None:
        cCodeToPyAstList(funcEnv, stmnt.body)
    cStatementToPyAst(funcEnv, stmnt.args[2])
    funcEnv.popScope()  # whileAst / main for-body

    funcEnv.popScope()  # ifAst
    return ifAst
Beispiel #8
0
    def _parse_iteration_statement(self, env):
        """ <iteration_statement>

        Parses the <iteration_statement> language structure.

            iteration_statement -> 'while' '(' logical_expressoin ')' statement
                                |   'do' statement 'while' '(' logical_expression ')'

        """
        if self._look.tag == lexer.Tag.WHILE:
            while_node = ast.While()
            save_stmt = ast.Statement.Enclosing
            ast.Statement.Enclosing = while_node
            self._match(lexer.Tag.WHILE, 'whild')
            self._match('(')
            expr = self._parse_logical_expression(env)
            self._match(')')
            stmt = self._parse_statement(env)
            while_node.init(expr, stmt)
            ast.Statement.Enclosing = save_stmt
            return while_node
        else:
            do_node = ast.Do()
            save_stmt = ast.Statement.Enclosing
            ast.Statement.Enclosing = do_node
            self._match(lexer.Tag.DO, 'do')
            stmt = self._parse_statement(env)
            self._match(lexer.Tag.WHILE, 'while')
            self._match('(')
            expr = self._parse_logical_expression(env)
            self._match(')')
            self._match(';')
            do_node.init(expr, stmt)
            ast.Statement.Enclosing = save_stmt
            return do_node
Beispiel #9
0
 def visit_While(self, node):
     self.generic_visit(node)
     return ast.copy_location(ast.While(
         test=self.wrap_test(node.test),
         body=node.body,
         orelse=node.orelse
     ), node)
Beispiel #10
0
    def visit_For(self, node):
        """ Change iteration into while-yield statements """
        # TODO: take care of StopIteration conversion?

        newnode = node

        if node in self.analysis.loopsToBeConverted:
            # For(expr target, expr iter, stmt* body, stmt* orelse)
            # While(expr test, stmt* body, stmt* orelse)

            # prepend statement to await a value in the coroutine
            newbody = [
                ast.Assign(targets=[node.target], value=ast.Yield(value=None))
            ] + node.body
            whileNode = ast.While(test=ast.Name(id=self.moreValuesAvailableId,
                                                ctx=ast.Load()),
                                  body=newbody,
                                  orelse=[])  # TODO: what to do with orelse

            newnode = self._tryExceptGeneratorExit(
                [whileNode],
                [self._moreValuesAvailableAssignmentNode('False')])

        self.generic_visit(newnode)

        return ast.copy_location(newnode, node)
Beispiel #11
0
 def while_to_node(self, while_statement):
     test_node = self.to_node(while_statement.test)
     body_node = list(
         map(lambda stmt: self.to_node(stmt), while_statement.body))
     orelse_node = self.orelse_to_node(while_statement.orelse)
     node = ast.While(test=test_node, body=body_node, orelse=orelse_node)
     return node
Beispiel #12
0
 def while_(self):
     self.expect('while')
     self.expect('(')
     cond = self.expression()
     self.expect(')')
     body = self.statement()
     return ast.While(cond, body)
Beispiel #13
0
def p_while_stmt(p):
    '''stmt : WHILE expression body
            | WHILE expression body ELSE body'''
    if len(p) == 6:
        orelse = p[5]
    else:
        orelse = []
    p[0] = ast.While(p[2], p[3], orelse)
Beispiel #14
0
 def python_ast(self):
     ptest = self.test.python_ast()
     pi = self.instructions.python_ast()
     #        ptest,pi,lineno=self.line,col_offset=self.column
     last = ast.While(lineno=self.line, col_offset=self.column)
     last.test = ptest
     last.body = pi
     last.orelse = []
     return last
Beispiel #15
0
def p_while_statement(p):
    '''
    while_statement : WHILE LPAREN expr RPAREN statement
    '''
    if DEBUG:
        print("\nwhile stmt: ", end="")
        for i in range(len(p)):
            print(i, " ", p[i], " ", end="")
    p[0] = ast.While(p[3], p[5])
Beispiel #16
0
 def visit_While(self, node):
     new_body = self.if_exists(node.body, self.visit_list)
     new_orelse = self.if_exists(node.orelse, self.visit_list)
     new_test = self.visit(node.test)
     return_list = self.new_stmts + [
         ast.copy_location(ast.While(new_test, new_body, new_orelse), node)
     ]
     self.new_stmts.clear()
     return return_list
Beispiel #17
0
 def wrap_func_body(self, flat_body):
     var_ast = ast.Assign()
     var_ast.targets = [ast.Name(id=self.gotoVarName, ctx=ast.Store())]
     var_ast.value = ast.Name(id="None", ctx=ast.Load())
     main_loop_ast = ast.While(orelse=[])
     main_loop_ast.test = ast.Name(id="True", ctx=ast.Load())
     main_loop_ast.body = self.handle_body(flat_body)
     main_loop_ast.body += [ast.Break()]
     return [var_ast, main_loop_ast]
Beispiel #18
0
 def to_node(self):
     test = self.condition.to_node()
     body = []
     for statement in self.body.statement:
         body.append(statement.to_node())
     orelse = []
     if self.else_body is not None:
         for statement in self.else_body.statement:
             orelse.append(statement.to_node())
     return ast.While(test=test, body=body, orelse=orelse)
Beispiel #19
0
    def compute_whileloop_stmt(self, stmt_iter):

        if len(self.stmt_cond) == 1:

            assert(isinstance(self.stmt_cond[0], ast.Assign) and isinstance(self.stmt_cond[0].value, ast.UnaryOp))

            negated_break_condition = self.stmt_cond[0].value

            assert(isinstance(negated_break_condition.op, ast.Not))

            break_condition = negated_break_condition.operand
            loop_stmt = [ast.While(test=break_condition,
                                                    body=stmt_iter, orelse=[])] + self.stmt_ret

        else:
            loop_stmt = self.stmt_cond + [ast.While(test=self.break_condition,
                                                body=(stmt_iter + self.stmt_cond), orelse=[])] + self.stmt_ret

        return loop_stmt
    def visit_While(self, node: While, *args, **kwargs) -> C.While:
        test = self.visit(node.test, *args, **kwargs)
        body = self.visit(node.body, *args, **kwargs)
        orelse = self.visit(node.orelse, *args, **kwargs)

        return C.While(
            test=test,
            body=body,
            orelse=orelse,
        )
Beispiel #21
0
    def visitWhile(self, node):
        #('test', 'body', 'orelse')
        if node.orelse:
            raise cast.CError(node, NotImplementedError,
                              "while ... else is not yet allowed in openCL")

        test = self.visit(node.test)
        body = list(self.visit_list(node.body))

        return ast.While(test, body, None)
Beispiel #22
0
 def test_break(self):
     assert self.run([
         ast.Assign(
             [ast_store('i')],
             ast.Num(0),
         ),
         ast.While(ast.Compare(ast_load('i'), [ast.Lt()], [ast.Num(10)]), [
             ast.Break(),
         ], [])
     ], 'i', int) == 0
Beispiel #23
0
        def visit_While(self, node):
            if self.done:
                return node
            if self.count != self.selection:
                self.count += 1
                return node

            self.done = True
            return ast.While(test=node.test,
                             body=node.body + [node, ast.Break()],
                             orelse=[])
Beispiel #24
0
def p_infinite_loop_stmt(t):
    '''stmt : LOOP suite'''
    one = ast.Num(1)
    one.lineno = t.lineno(1)
    one.col_offset = -1  # XXX

    suite = t[2]

    t[0] = ast.While(one, suite, [])
    t[0].lineno = t.lineno(1)
    t[0].col_offset = -1  # XXX
Beispiel #25
0
    def compile_while_expression(self, expr):
        expr.pop(0)  # "while"
        test = self.compile(expr.pop(0))

        return ast.While(
            test=test,
            body=self._code_branch([self.compile(x) for x in expr],
                                   expr.start_line, expr.start_column),
            orelse=[],
            lineno=expr.start_line,
            col_offset=expr.start_column)
Beispiel #26
0
def loop(self, tree):
    if 'loop' in self.templates:
        return self.node(
            tmp='loop',
            parts={
                'body': expression_block(self, tree),
            }
        )
    return self.visit(ast.While(
        test=ast.Constant(value=True),
        body=tree
    ))
Beispiel #27
0
def p_for_stmt(p):
    '''stmt : FOR expression body body body
            | FOR expression body body body ELSE body'''
    if len(p) == 8:
        orelse = p[7]
    else:
        orelse = []

    p[5].extend(p[4])
    whilel = ast.While(p[2], p[5], orelse)
    p[3].append(whilel)
    p[0] = whilel
Beispiel #28
0
def _make_for_loops_while(parent_node, names_in_use):
    """Converts for loops into while loops.
    Creates an index variable and a call to the len() function as a test for the while loop.
    All for loop iterators must be indexable. DOES NOT SUPPOT NONINDEXABLE ITERATORS.
    Parameters:
        parent_node: ast node
    Returns:
        parent node with updates"""

    #get every index of for loop objects in the body of parent node. Could be done cleaner with a numpy .where,
    #but we'd have to import numpy pretty much just for that.
    try:
        indices_of_for_loops = list(filter(lambda index: isinstance(parent_node.body[index], ast.For),
                                            range(len(parent_node.body))))
    except:
        #node has no body. No for loops in it.
        return parent_node, names_in_use

    for for_loop_index in indices_of_for_loops:
        for_loop = parent_node.body[for_loop_index]

        #make loop incrementor variable
        name_incrementor_variable = _new_name('loop_index', names_in_use)
        names_in_use[name_incrementor_variable] = 1

        #make a call to built in len() function with the iterator provided in the for loop
        len_builtin_function = ast.Name(id='len', ctx=ast.Load)
        len_function_call = ast.Call(func=len_builtin_function, args=[for_loop.iter], keywords=[])

        #test for while loop
        compare_op = ast.Compare(ast.Name(name_incrementor_variable, ctx=ast.Load),
             ops=[ast.Lt()], comparators=[len_function_call])

        #assign current value of loop to for loop target
        assign_to_for_loop_target = ast.Assign([for_loop.target],
            ast.Subscript(for_loop.iter, ast.Index(ast.Name(id=name_incrementor_variable, ctx=ast.Load))))

        #increment index variable
        add_1_to_index_variable = ast.AugAssign(ast.Name(id=name_incrementor_variable), ast.Add(), ast.Num(1))

        #construct while loop
        while_loop_body = [assign_to_for_loop_target] + \
            for_loop.body + [add_1_to_index_variable]
        while_loop = ast.While(test=compare_op, body= while_loop_body, orelse=[])

        #replace for with while loop
        parent_node.body[for_loop_index] = while_loop

        #insert loop incrementor variabel before while loop and set to 0
        parent_node.body.insert(for_loop_index - 1,
            ast.Assign([ast.Name(id=name_incrementor_variable, ctx=ast.Store)], ast.Num(0)))

    return parent_node, names_in_use
Beispiel #29
0
    def visit_While(self, while_stmt: ast.While) -> ActionsT:
        test, test_actions = self.visit_expr(while_stmt.test)

        self.loop_cond_actions.append(test_actions)
        body = self.visit_stmt_list(while_stmt.body)
        self.loop_cond_actions.pop()
        body += test_actions  # Re-compute loop condition at the end of loop body.

        if while_stmt.orelse:
            raise NodeNotSupportedError(while_stmt, "While statement orelse not supported.")
        result_node = ast.While(test=test, body=body, orelse=[])
        return test_actions + [result_node]
Beispiel #30
0
    def while_loop(self):
        self.lexer.match("while")
        condition, statements = self.expr(), []
        self.lexer.match(":")
        self.lexer.match_type(TokenType.EndOfLine)
        self.lexer.match_type(TokenType.StartOfBlock)

        while self.lexer.waiting_for_type(TokenType.EndOfBlock):
            statements.append(self.statement())
        self.lexer.next()  # Pass through EndOfBlock

        return ast.While(condition, statements)