Python ast.If() Examples

The following are 30 code examples of ast.If(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ast , or try the search function .
Example #1
Source File: topython.py    From pyrser with GNU General Public License v3.0 6 votes vote down vote up
def visit_Rep0N(self, node: parsing.Rep0N) -> [ast.stmt]:
        """Generates python code for a clause repeated 0 or more times.

        #If all clauses can be inlined
        while clause:
            pass

        while True:
            <code for the clause>
        """
        cl_ast = self.visit(node.pt)
        if isinstance(cl_ast, ast.expr):
            return [ast.While(cl_ast, [ast.Pass()], [])]
        self.in_loop += 1
        clause = self._clause(self.visit(node.pt))
        self.in_loop -= 1
        return [ast.While(ast.Name('True', ast.Load()), clause, [])] 
Example #2
Source File: stmt_visitor.py    From pyt with GNU General Public License v2.0 6 votes vote down vote up
def handle_or_else(self, orelse, test):
        """Handle the orelse part of an if or try node.

        Args:
            orelse(list[Node])
            test(Node)

        Returns:
            The last nodes of the orelse branch.
        """
        if isinstance(orelse[0], ast.If):
            control_flow_node = self.visit(orelse[0])
            # Prefix the if label with 'el'
            control_flow_node.test.label = 'el' + control_flow_node.test.label

            test.connect(control_flow_node.test)
            return control_flow_node.last_nodes
        else:
            else_connect_statements = self.stmt_star_handler(
                orelse,
                prev_node_to_avoid=self.nodes[-1]
            )
            test.connect(else_connect_statements.first_statement)
            return else_connect_statements.last_statements 
Example #3
Source File: _toVHDL.py    From myhdl with GNU Lesser General Public License v2.1 6 votes vote down vote up
def manageEdges(self, ifnode, senslist):
        """ Helper method to convert MyHDL style template into VHDL style"""
        first = senslist[0]
        if isinstance(first, _WaiterList):
            bt = _WaiterList
        elif isinstance(first, _Signal):
            bt = _Signal
        elif isinstance(first, delay):
            bt = delay
        assert bt
        for e in senslist:
            if not isinstance(e, bt):
                self.raiseError(ifnode, "base type error in sensitivity list")
        if len(senslist) >= 2 and bt == _WaiterList:
            # ifnode = node.code.nodes[0]
            # print ifnode
            assert isinstance(ifnode, ast.If)
            asyncEdges = []
            for test, suite in ifnode.tests:
                e = self.getEdge(test)
                if e is None:
                    self.raiseError(ifnode, "No proper edge value test")
                asyncEdges.append(e)
            if not ifnode.else_:
                self.raiseError(ifnode, "No separate else clause found")
            edges = []
            for s in senslist:
                for e in asyncEdges:
                    if s is e:
                        break
                else:
                    edges.append(s)
            ifnode.edge = edges
            senslist = [s.sig for s in senslist]
        return senslist 
Example #4
Source File: setup_reader.py    From poetry with MIT License 6 votes vote down vote up
def _find_sub_setup_call(
        self, elements
    ):  # type: (List[Any]) -> Tuple[Optional[ast.Call], Optional[List[Any]]]
        for element in elements:
            if not isinstance(element, (ast.FunctionDef, ast.If)):
                continue

            setup_call = self._find_setup_call(element.body)
            if setup_call != (None, None):
                setup_call, body = setup_call

                body = elements + body

                return setup_call, body

        return None, None 
Example #5
Source File: _343.py    From codetransformer with GNU General Public License v2.0 6 votes vote down vote up
def make_assignment(instr, queue, stack):
    """
    Make an ast.Assign node.
    """
    value = make_expr(stack)

    # Make assignment targets.
    # If there are multiple assignments (e.g. 'a = b = c'),
    # each LHS expression except the last is preceded by a DUP_TOP instruction.
    # Thus, we make targets until we don't see a DUP_TOP, and then make one
    # more.
    targets = []
    while isinstance(instr, instrs.DUP_TOP):
        targets.append(make_assign_target(queue.popleft(), queue, stack))
        instr = queue.popleft()

    targets.append(make_assign_target(instr, queue, stack))

    return ast.Assign(targets=targets, value=value) 
Example #6
Source File: model.py    From staticfg with Apache License 2.0 6 votes vote down vote up
def get_source(self):
        """
        Get a string containing the Python source code corresponding to the
        statements in the block.

        Returns:
            A string containing the source code of the statements.
        """
        src = ""
        for statement in self.statements:
            if type(statement) in [ast.If, ast.For, ast.While]:
                src += (astor.to_source(statement)).split('\n')[0] + "\n"
            elif type(statement) == ast.FunctionDef or\
                 type(statement) == ast.AsyncFunctionDef:
                src += (astor.to_source(statement)).split('\n')[0] + "...\n"
            else:
                src += astor.to_source(statement)
        return src 
Example #7
Source File: syntax.py    From fiasko_bro with MIT License 6 votes vote down vote up
def indent_not_multiple_of_tab_size(project_folder, tab_size, *args, **kwargs):
    """
        Since there are cases for which col_offset is computed incorrectly,
        this validator must be nothing more than a simple warning.

        It compliments the pep8 validator which tends to fail in cases when
        the indent is incorrect.
    """
    node_types_to_validate = (ast.For, ast.If, ast.FunctionDef, ast.With)
    for parsed_file in project_folder.get_parsed_py_files():
        lines_offsets = file_helpers.get_line_offsets(parsed_file.content)
        for node in ast.walk(parsed_file.ast_tree):
            if not ast_helpers.is_node_offset_fine(
                node,
                lines_offsets,
                node_types_to_validate,
                tab_size,
            ):
                return parsed_file.get_name_with_line(node.lineno) 
Example #8
Source File: readers.py    From pdm with MIT License 6 votes vote down vote up
def _find_sub_setup_call(
        self, elements
    ):  # type: (List[Any]) -> Tuple[Optional[ast.Call], Optional[List[Any]]]
        for element in elements:
            if not isinstance(element, (ast.FunctionDef, ast.If)):
                continue

            setup_call = self._find_setup_call(element.body)
            if setup_call != (None, None):
                setup_call, body = setup_call

                body = elements + body

                return setup_call, body

        return None, None 
Example #9
Source File: ast_translator.py    From pseudo-python with MIT License 6 votes vote down vote up
def _translate_if(self, test, orelse, body, location, base=True):
        test_node = self._testable(self._translate_node(test))
        block = self._translate_node(body)
        #block [self._translate_node(child) for child in body]
        if orelse and len(orelse) == 1 and isinstance(orelse[0], ast.If):
            otherwise = self._translate_if(orelse[0].test, orelse[0].orelse, orelse[0].body, location, False)
        elif orelse:
            otherwise = {
                'type': 'else_statement',
                'block': self._translate_node(orelse),
                #block [self._translate_node(node) for node in orelse],
                'pseudo_type': 'Void'
            }
        else:
            otherwise = None

        return {
            'type': 'if_statement' if base else 'elseif_statement',
            'test': test_node,
            'block': block,
            'pseudo_type': 'Void',
            'otherwise': otherwise
        } 
Example #10
Source File: parser.py    From vecpy with MIT License 6 votes vote down vote up
def while_(self, block, src):
    #Mark the start and stop indices for the while condition so it can be checked later
    start_index = len(block.code)
    #Parse the condition
    cond = self.expression(block, src.test)
    #Generate the mask
    mask = self.get_mask(block, cond, Operator.bit_and)
    stop_index = len(block.code)
    loop = WhileLoop(mask)
    #Recursively parse the body
    for stmt in src.body:
      self.statement(loop.block, stmt)
    #Duplicate the condition checking code
    self.add_comment(loop.block, src)
    loop.block.code += block.code[start_index:stop_index]
    #Nest the loop in the current block
    block.add(loop)

  #Parses an if(-else) statement (AST If) 
Example #11
Source File: node_transformers.py    From pynt with GNU General Public License v3.0 6 votes vote down vote up
def visit_Module(self, module):
        """Maybe replace the entire module with a kernel

        If namespace is targeting the top-level then we do it.

        >>> self = IPythonEmbedder(namespace='foo.foo')
        >>> code = '''
        ...
        ... import random
        ... def foo():
        ...     pass
        ...
        ... '''
        >>> module = ast.parse(code)

        """
        if self.func_type == 'module':
            module.body = self.get_kernel_embed()
        else:
            module = self.generic_visit(module)
        return module 
Example #12
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_if_stmt_1(p):
    '''if_stmt : IF test COLON suite'''
    #             1    2     3     4
    p[0] = ast.If(p[2], p[4], [], rule=inspect.currentframe().f_code.co_name, **p[1][1]) 
Example #13
Source File: parser.py    From myia with MIT License 5 votes vote down vote up
def process_If(self, block: "Block", node: ast.If) -> "Block":
        """Process a conditional statement.

        A conditional statement generates 3 functions: The true branch, the
        false branch, and the continuation.
        """
        # Process the condition
        cond = self.process_node(block, node.test)

        # Create two branches
        true_block, false_block = self.make_condition_blocks(block)
        true_block.graph.debug.location = self.make_location(node.body)
        false_block.graph.debug.location = self.make_location(node.orelse)

        # Create the continuation
        with About(block.graph.debug, "if_after"):
            after_block = self.new_block(auxiliary=True)

        # Process the first branch
        true_end = self.process_statements(true_block, node.body)
        # A return statement in the branch might mean that a continuation has
        # already been set
        if not true_end.graph.return_:
            true_end.jump(after_block)

        # And the second
        false_end = self.process_statements(false_block, node.orelse)
        if not false_end.graph.return_:
            false_end.jump(after_block)

        # And stich it together
        block.cond(cond, true_block, false_block)
        after_block.mature()
        return after_block 
Example #14
Source File: checker.py    From pyflakes with MIT License 5 votes vote down vote up
def getAlternatives(n):
        if isinstance(n, (ast.If, ast.TryFinally)):
            return [n.body]
        if isinstance(n, ast.TryExcept):
            return [n.body + n.orelse] + [[hdl] for hdl in n.handlers] 
Example #15
Source File: parser.py    From myia with MIT License 5 votes vote down vote up
def _fresh(node):
    """If node is a constant, return a copy of it."""
    if node.is_constant_graph():
        return Constant(node.value)
    else:
        return node 
Example #16
Source File: parser.py    From vecpy with MIT License 5 votes vote down vote up
def statement(self, block, stmt):
    #Add a comment
    self.add_comment(block, stmt)
    #Parse the statement
    try:
      if isinstance(stmt, ast.Assign):
        self.assign(block, stmt)
      elif isinstance(stmt, ast.Return):
        self.return_(block, stmt)
      elif isinstance(stmt, ast.Expr):
        self.docstring_(block, stmt)
      elif isinstance(stmt, ast.If):
        self.if_(block, stmt)
      elif isinstance(stmt, ast.While):
        self.while_(block, stmt)
      elif isinstance(stmt, ast.AugAssign):
        self.augassign(block, stmt)
      else:
        Parser._dump(stmt, 'Unexpected Statement')
        raise Exception('Unexpected Statement (%s)'%(stmt.__class__))
    except:
      line = stmt.lineno
      src = self.source.split('\n')[line - 1].strip()
      print('Line %d: %s'%(line, src))
      raise

  #===========================================================
  # Public interface
  #===========================================================
  #Parses the kernel using the specified live function 
Example #17
Source File: walkers.py    From jishaku with MIT License 5 votes vote down vote up
def visit_Return(self, node):
        # Do not modify valueless returns
        if node.value is None:
            return node

        # Otherwise, replace the return with a yield & valueless return
        return ast.If(
            test=ast.NameConstant(
                value=True,  # if True; aka unconditional, will be optimized out
                lineno=node.lineno,
                col_offset=node.col_offset
            ),
            body=[
                # yield the value to be returned
                ast.Expr(
                    value=ast.Yield(
                        value=node.value,
                        lineno=node.lineno,
                        col_offset=node.col_offset
                    ),
                    lineno=node.lineno,
                    col_offset=node.col_offset
                ),
                # return valuelessly
                ast.Return(
                    value=None,
                    lineno=node.lineno,
                    col_offset=node.col_offset
                )
            ],
            orelse=[],
            lineno=node.lineno,
            col_offset=node.col_offset
        ) 
Example #18
Source File: utils.py    From BibleBot with GNU General Public License v3.0 5 votes vote down vote up
def insert_returns(body):  # for +eval, thanks to nitros12 on github for the code
    # insert return stmt if the last expression is a expression statement
    if isinstance(body[-1], ast.Expr):
        body[-1] = ast.Return(body[-1].value)
        ast.fix_missing_locations(body[-1])

    # for if statements, we insert returns into the body and the orelse
    if isinstance(body[-1], ast.If):
        insert_returns(body[-1].body)
        insert_returns(body[-1].orelse)

    # for with blocks, again we insert returns into the body
    if isinstance(body[-1], ast.With):
        insert_returns(body[-1].body) 
Example #19
Source File: _343.py    From codetransformer with GNU General Public License v2.0 5 votes vote down vote up
def make_if_statement(instr, queue, stack, context):
    """
    Make an ast.If block from a POP_JUMP_IF_TRUE or POP_JUMP_IF_FALSE.
    """
    test_expr = make_expr(stack)
    if isinstance(instr, instrs.POP_JUMP_IF_TRUE):
        test_expr = ast.UnaryOp(op=ast.Not(), operand=test_expr)

    first_block = popwhile(op.is_not(instr.arg), queue, side='left')
    if isinstance(first_block[-1], instrs.RETURN_VALUE):
        body = instrs_to_body(first_block, context)
        return ast.If(test=test_expr, body=body, orelse=[])

    jump_to_end = expect(
        first_block.pop(), instrs.JUMP_FORWARD, "at end of if-block"
    )

    body = instrs_to_body(first_block, context)

    # First instruction after the whole if-block.
    end = jump_to_end.arg
    if instr.arg is jump_to_end.arg:
        orelse = []
    else:
        orelse = instrs_to_body(
            popwhile(op.is_not(end), queue, side='left'),
            context,
        )

    return ast.If(test=test_expr, body=body, orelse=orelse) 
Example #20
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_if_stmt_3(p):
    '''if_stmt : IF test COLON suite if_stmt_star'''
    #             1    2     3     4            5
    p[0] = ast.If(p[2], p[4], [p[5]], rule=inspect.currentframe().f_code.co_name, **p[1][1]) 
Example #21
Source File: parser.py    From myia with MIT License 5 votes vote down vote up
def process_statements(
        self, starting_block: "Block", nodes: List[ast.stmt]
    ) -> "Block":
        """Process a sequence of statements.

        If the list of statements is empty, a new empty block will be
        constructed and returned. This ensures that empty code blocks (e.g. an
        empty else branch) still have a corresponding block that can be used to
        call the continuation from.

        """
        block = starting_block
        for node in nodes:
            block = self.process_node(block, node, used=False)
        return block 
Example #22
Source File: parser.py    From myia with MIT License 5 votes vote down vote up
def process_FunctionDef(
        self, block: "Block", node: ast.FunctionDef
    ) -> "Block":
        """Process a function definition.

        Args:
            block: Predecessor block (optional). If given, this is a nested
                function definition.
            node: The function definition.

        """
        function_block, process = self._create_function(block, node)
        block.write(node.name, Constant(function_block.graph), track=False)
        self.finalizers[function_block.graph] = process
        return block 
Example #23
Source File: stmt_visitor.py    From pyt with GNU General Public License v2.0 5 votes vote down vote up
def process_loop_funcs(self, comp_n, loop_node):
        """
        If the loop test node contains function calls, it connects the loop node to the nodes of
        those function calls.

        :param comp_n: The test node of a loop that may contain functions.
        :param loop_node: The loop node itself to connect to the new function nodes if any
        :return: None
        """
        if isinstance(comp_n, ast.Call) and get_call_names_as_string(comp_n.func) in self.function_names:
            last_node = self.visit(comp_n)
            last_node.connect(loop_node) 
Example #24
Source File: traceback.py    From myia with MIT License 5 votes vote down vote up
def skip_node(node):
    """Whether to skip a step in the traceback based on ast node type."""
    return isinstance(node, (ast.If, ast.While, ast.For)) 
Example #25
Source File: test_ast.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_if(self):
        self.stmt(ast.If(ast.Num(3), [], []), "empty body on If")
        i = ast.If(ast.Name("x", ast.Store()), [ast.Pass()], [])
        self.stmt(i, "must have Load context")
        i = ast.If(ast.Num(3), [ast.Expr(ast.Name("x", ast.Store()))], [])
        self.stmt(i, "must have Load context")
        i = ast.If(ast.Num(3), [ast.Pass()],
                   [ast.Expr(ast.Name("x", ast.Store()))])
        self.stmt(i, "must have Load context") 
Example #26
Source File: manhole.py    From mautrix-python with Mozilla Public License 2.0 5 votes vote down vote up
def insert_returns(body: List[ast.AST]) -> None:
    if isinstance(body[-1], ast.Expr):
        body[-1] = ast.Return(body[-1].value)
        ast.fix_missing_locations(body[-1])
    elif isinstance(body[-1], ast.If):
        insert_returns(body[-1].body)
        insert_returns(body[-1].orelse)
    elif isinstance(body[-1], (ast.With, ast.AsyncWith)):
        insert_returns(body[-1].body) 
Example #27
Source File: nodevisitor.py    From python-lua with Apache License 2.0 5 votes vote down vote up
def visit_If(self, node):
        """Visit if"""
        test = self.visit_all(node.test, inline=True)

        line = "if {} then".format(test)

        self.emit(line)
        self.visit_all(node.body)

        if node.orelse:
            if isinstance(node.orelse[0], ast.If):
                elseif = node.orelse[0]
                elseif_test = self.visit_all(elseif.test, inline=True)

                line = "elseif {} then".format(elseif_test)
                self.emit(line)

                output_length = len(self.output)
                self.visit_If(node.orelse[0])

                del self.output[output_length]
                del self.output[-1]
            else:
                self.emit("else")
                self.visit_all(node.orelse)

        self.emit("end") 
Example #28
Source File: test_ast.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_if(self):
        self.stmt(ast.If(ast.Num(3), [], []), "empty body on If")
        i = ast.If(ast.Name("x", ast.Store()), [ast.Pass()], [])
        self.stmt(i, "must have Load context")
        i = ast.If(ast.Num(3), [ast.Expr(ast.Name("x", ast.Store()))], [])
        self.stmt(i, "must have Load context")
        i = ast.If(ast.Num(3), [ast.Pass()],
                   [ast.Expr(ast.Name("x", ast.Store()))])
        self.stmt(i, "must have Load context") 
Example #29
Source File: modules.py    From ansible-testing with GNU General Public License v3.0 5 votes vote down vote up
def _find_main_call(self):
        lineno = False
        if_bodies = []
        for child in self.ast.body:
            if isinstance(child, ast.If):
                try:
                    if child.test.left.id == '__name__':
                        if_bodies.extend(child.body)
                except AttributeError:
                    pass

        bodies = self.ast.body
        bodies.extend(if_bodies)

        for child in bodies:
            if isinstance(child, ast.Expr):
                if isinstance(child.value, ast.Call):
                    if (isinstance(child.value.func, ast.Name) and
                            child.value.func.id == 'main'):
                        lineno = child.lineno
                        if lineno < self.length - 1:
                            self.errors.append('Call to main() not the last '
                                               'line')

        if not lineno:
            self.errors.append('Did not find a call to main')

        return lineno or 0 
Example #30
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_if_stmt_4(p):
    '''if_stmt : IF test COLON suite if_stmt_star ELSE COLON suite'''
    #             1    2     3     4            5    6     7     8
    last = p[5]
    while len(last.orelse) > 0:
        last = last.orelse[0]
    last.orelse.extend(p[8])
    p[0] = ast.If(p[2], p[4], [p[5]], rule=inspect.currentframe().f_code.co_name, **p[1][1])