Python ast.Or() Examples

The following are 30 code examples of ast.Or(). 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: yacc.py    From yaksok with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def p_logic_or_expr(t):
    '''logic_or_expr : logic_or_expr OR logic_and_expr
                     | logic_and_expr'''
    if len(t) == 4:
        if isinstance(t[1], ast.BoolOp) and isinstance(t[1].op, ast.Or):
            t[0] = t[1]
            t[0].values.append(t[3])
        else:
            or_ast = ast.Or()
            or_ast.lineno = t.lineno(2)
            or_ast.col_offset = -1 # XXX
            t[0] = ast.BoolOp(or_ast, [t[1], t[3]])
            t[0].lineno = t.lineno(2)
            t[0].col_offset = -1 # XXX
    else:
        t[0] = t[1] 
Example #2
Source File: test_transformers.py    From mutatest with MIT License 6 votes vote down vote up
def test_MutateAST_visit_boolop(boolop_file, boolop_expected_loc):
    """Test mutation of AND to OR in the boolop."""
    tree = Genome(boolop_file).ast
    test_mutation = ast.Or

    # apply the mutation to the original tree copy
    testing_tree = deepcopy(tree)
    mutated_tree = MutateAST(target_idx=boolop_expected_loc, mutation=test_mutation).visit(
        testing_tree
    )

    # revisit in read-only mode to gather the locations of the new nodes
    mast = MutateAST(readonly=True)
    mast.visit(mutated_tree)

    # four locations from the binary operations in binop_file
    assert len(mast.locs) == 1

    # there will only be one loc, but this still works
    # basedon the col and line offset in the fixture for compare_expected_loc
    for loc in mast.locs:
        if loc.lineno == 2 and loc.col_offset == 11:
            assert loc.op_type == test_mutation 
Example #3
Source File: isolate_format.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def verify_ast(expr, variables_and_values):
  """Verifies that |expr| is of the form
  expr ::= expr ( "or" | "and" ) expr
         | identifier "==" ( string | int )
  Also collects the variable identifiers and string/int values in the dict
  |variables_and_values|, in the form {'var': set([val1, val2, ...]), ...}.
  """
  assert isinstance(expr, (ast.BoolOp, ast.Compare))
  if isinstance(expr, ast.BoolOp):
    assert isinstance(expr.op, (ast.And, ast.Or))
    for subexpr in expr.values:
      verify_ast(subexpr, variables_and_values)
  else:
    assert isinstance(expr.left.ctx, ast.Load)
    assert len(expr.ops) == 1
    assert isinstance(expr.ops[0], ast.Eq)
    var_values = variables_and_values.setdefault(expr.left.id, set())
    rhs = expr.comparators[0]
    assert isinstance(rhs, (ast.Str, ast.Num))
    var_values.add(rhs.n if isinstance(rhs, ast.Num) else rhs.s) 
Example #4
Source File: parser.py    From vecpy with MIT License 6 votes vote down vote up
def boolop(self, block, node, var=None):
    #Get the type of operation
    if isinstance(node.op, ast.And):
      op = Operator.bool_and
    elif isinstance(node.op, ast.Or):
      op = Operator.bool_or
    else:
      raise Exception('Unexpected BoolOp (%s)'%(node.op.__class__))
    #Chain operations together
    left = self.expression(block, node.values[0])
    for node_value in node.values[1:]:
      right = self.expression(block, node_value)
      operation = BinaryOperation(left, op, right)
      if node_value == node.values[-1] and var is not None:
        #The last operation in the chain should be assigned to this variable
        temp_var = var
      else:
        #Create a temporary variable to store the intermediate result
        temp_var = self.add_variable(None, is_mask=True)
      assignment = Assignment(temp_var, operation)
      block.add(assignment)
      left = temp_var
    return temp_var

  #Parses an array element (AST Subscript) 
Example #5
Source File: _343.py    From codetransformer with GNU General Public License v2.0 6 votes vote down vote up
def normalize_boolop(expr):
    """
    Normalize a boolop by folding together nested And/Or exprs.
    """
    optype = expr.op
    newvalues = []
    for subexpr in expr.values:
        if not isinstance(subexpr, ast.BoolOp):
            newvalues.append(subexpr)
        elif type(subexpr.op) != type(optype):
            newvalues.append(normalize_boolop(subexpr))
        else:
            # Normalize subexpression, then inline its values into the
            # top-level subexpr.
            newvalues.extend(normalize_boolop(subexpr).values)
    return ast.BoolOp(op=optype, values=newvalues) 
Example #6
Source File: python2ir.py    From ppci with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def gen_bool_op(self, condition, yes_block, no_block):
        """ Compile a boolean operator such as 'and' """
        assert len(condition.values) >= 1
        first_values = condition.values[:-1]
        last_value = condition.values[-1]
        if isinstance(condition.op, ast.And):
            # All values must be true here,
            # so bail out on first false value.
            for value in first_values:
                all_true_block = self.builder.new_block()
                self.gen_cond(value, all_true_block, no_block)
                self.builder.set_block(all_true_block)

            self.gen_cond(last_value, yes_block, no_block)
        elif isinstance(condition.op, ast.Or):
            # The first true value is enough to make this work!
            for value in first_values:
                all_false_block = self.builder.new_block()
                self.gen_cond(value, yes_block, all_false_block)
                self.builder.set_block(all_false_block)

            self.gen_cond(last_value, yes_block, no_block)
        else:  # pragma: no cover
            self.not_impl(condition) 
Example #7
Source File: tags_manager.py    From golem with MIT License 6 votes vote down vote up
def _evaluate(self, expr):
        if isinstance(expr, ast.Expr):
            return self._evaluate(expr.value)
        elif isinstance(expr, ast.BoolOp):
            if isinstance(expr.op, ast.Or):
                evaluated = ['({})'.format(self._evaluate(v)) for v in expr.values]
                return ' or '.join(evaluated)
            elif isinstance(expr.op, ast.And):
                evaluated = ['({})'.format(self._evaluate(v)) for v in expr.values]
                return ' and '.join(evaluated)
        elif isinstance(expr, ast.UnaryOp):
            if isinstance(expr.op, ast.Not):
                return 'not {}'.format(self._evaluate(expr.operand))
        elif isinstance(expr, ast.Num):
            return '"{}" in {}'.format(str(expr.n), self.tags)
        elif isinstance(expr, ast.Str):
            return '"{}" in {}'.format(expr.s, self.tags)
        elif isinstance(expr, ast.Name):
            return '"{}" in {}'.format(expr.id, self.tags)
        else:
            msg = ('unknown expression {}, the only valid operators for tag expressions '
                   'are: \'and\', \'or\' & \'not\''.format(type(expr)))
            raise InvalidTagExpression(msg) 
Example #8
Source File: markers.py    From datafari with Apache License 2.0 5 votes vote down vote up
def do_boolop(self, node):
        result = self.evaluate(node.values[0])
        is_or = node.op.__class__ is ast.Or
        is_and = node.op.__class__ is ast.And
        assert is_or or is_and
        if (is_and and result) or (is_or and not result):
            for n in node.values[1:]:
                result = self.evaluate(n)
                if (is_or and result) or (is_and and not result):
                    break
        return result 
Example #9
Source File: markers.py    From Flask with Apache License 2.0 5 votes vote down vote up
def do_boolop(self, node):
        result = self.evaluate(node.values[0])
        is_or = node.op.__class__ is ast.Or
        is_and = node.op.__class__ is ast.And
        assert is_or or is_and
        if (is_and and result) or (is_or and not result):
            for n in node.values[1:]:
                result = self.evaluate(n)
                if (is_or and result) or (is_and and not result):
                    break
        return result 
Example #10
Source File: markers.py    From Flask with Apache License 2.0 5 votes vote down vote up
def do_boolop(self, node):
        result = self.evaluate(node.values[0])
        is_or = node.op.__class__ is ast.Or
        is_and = node.op.__class__ is ast.And
        assert is_or or is_and
        if (is_and and result) or (is_or and not result):
            for n in node.values[1:]:
                result = self.evaluate(n)
                if (is_or and result) or (is_and and not result):
                    break
        return result 
Example #11
Source File: markers.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def do_boolop(self, node):
        result = self.evaluate(node.values[0])
        is_or = node.op.__class__ is ast.Or
        is_and = node.op.__class__ is ast.And
        assert is_or or is_and
        if (is_and and result) or (is_or and not result):
            for n in node.values[1:]:
                result = self.evaluate(n)
                if (is_or and result) or (is_and and not result):
                    break
        return result 
Example #12
Source File: markers.py    From ImageFusion with MIT License 5 votes vote down vote up
def do_boolop(self, node):
        result = self.evaluate(node.values[0])
        is_or = node.op.__class__ is ast.Or
        is_and = node.op.__class__ is ast.And
        assert is_or or is_and
        if (is_and and result) or (is_or and not result):
            for n in node.values[1:]:
                result = self.evaluate(n)
                if (is_or and result) or (is_and and not result):
                    break
        return result 
Example #13
Source File: markers.py    From ImageFusion with MIT License 5 votes vote down vote up
def do_boolop(self, node):
        result = self.evaluate(node.values[0])
        is_or = node.op.__class__ is ast.Or
        is_and = node.op.__class__ is ast.And
        assert is_or or is_and
        if (is_and and result) or (is_or and not result):
            for n in node.values[1:]:
                result = self.evaluate(n)
                if (is_or and result) or (is_and and not result):
                    break
        return result 
Example #14
Source File: _343.py    From codetransformer with GNU General Public License v2.0 5 votes vote down vote up
def make_boolop(exprs, op_types):
    """
    Parameters
    ----------
    exprs : deque
    op_types : deque[{ast.And, ast.Or}]
    """
    if len(op_types) > 1:
        return ast.BoolOp(
            op=op_types.popleft(),
            values=[exprs.popleft(), make_boolop(exprs, op_types)],
        )

    assert len(exprs) == 2
    return ast.BoolOp(op=op_types.popleft(), values=list(exprs)) 
Example #15
Source File: parser.py    From incubator-tvm with Apache License 2.0 5 votes vote down vote up
def visit_BoolOp(self, node):
        n = len(node.values)
        if n == 1:
            _internal_assert(isinstance(node.op, ast.Not), \
                             "Unary is supposed to be not!")
            return operator.not_(self.visit(node.values[0]))
        _internal_assert(isinstance(node.op, (ast.And, ast.Or)), \
                         "Binary is supposed to be and/or!")
        values = [self.visit(i) for i in node.values]
        return HybridParser._binop_maker[type(node.op)](*values) 
Example #16
Source File: markers.py    From python2017 with MIT License 5 votes vote down vote up
def do_boolop(self, node):
        result = self.evaluate(node.values[0])
        is_or = node.op.__class__ is ast.Or
        is_and = node.op.__class__ is ast.And
        assert is_or or is_and
        if (is_and and result) or (is_or and not result):
            for n in node.values[1:]:
                result = self.evaluate(n)
                if (is_or and result) or (is_and and not result):
                    break
        return result 
Example #17
Source File: markers.py    From Ansible with MIT License 5 votes vote down vote up
def do_boolop(self, node):
        result = self.evaluate(node.values[0])
        is_or = node.op.__class__ is ast.Or
        is_and = node.op.__class__ is ast.And
        assert is_or or is_and
        if (is_and and result) or (is_or and not result):
            for n in node.values[1:]:
                result = self.evaluate(n)
                if (is_or and result) or (is_and and not result):
                    break
        return result 
Example #18
Source File: markers.py    From Hands-On-Deep-Learning-for-Games with MIT License 5 votes vote down vote up
def do_boolop(self, node):
        result = self.evaluate(node.values[0])
        is_or = node.op.__class__ is ast.Or
        is_and = node.op.__class__ is ast.And
        assert is_or or is_and
        if (is_and and result) or (is_or and not result):
            for n in node.values[1:]:
                result = self.evaluate(n)
                if (is_or and result) or (is_and and not result):
                    break
        return result 
Example #19
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_or_test_2(p):
    '''or_test : and_test or_test_star'''
    #                   1            2
    theor = ast.Or(rule=inspect.currentframe().f_code.co_name)
    inherit_lineno(theor, p[2][0])
    p[0] = ast.BoolOp(theor, [p[1]] + p[2], rule=inspect.currentframe().f_code.co_name)
    inherit_lineno(p[0], p[1]) 
Example #20
Source File: markers.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def do_boolop(self, node):
        result = self.evaluate(node.values[0])
        is_or = node.op.__class__ is ast.Or
        is_and = node.op.__class__ is ast.And
        assert is_or or is_and
        if (is_and and result) or (is_or and not result):
            for n in node.values[1:]:
                result = self.evaluate(n)
                if (is_or and result) or (is_and and not result):
                    break
        return result 
Example #21
Source File: markers.py    From PhonePi_SampleServer with MIT License 5 votes vote down vote up
def do_boolop(self, node):
        result = self.evaluate(node.values[0])
        is_or = node.op.__class__ is ast.Or
        is_and = node.op.__class__ is ast.And
        assert is_or or is_and
        if (is_and and result) or (is_or and not result):
            for n in node.values[1:]:
                result = self.evaluate(n)
                if (is_or and result) or (is_and and not result):
                    break
        return result 
Example #22
Source File: markers.py    From planespotter with MIT License 5 votes vote down vote up
def do_boolop(self, node):
        result = self.evaluate(node.values[0])
        is_or = node.op.__class__ is ast.Or
        is_and = node.op.__class__ is ast.And
        assert is_or or is_and
        if (is_and and result) or (is_or and not result):
            for n in node.values[1:]:
                result = self.evaluate(n)
                if (is_or and result) or (is_and and not result):
                    break
        return result 
Example #23
Source File: conditions.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def _check_isinstance_calls(self, node: ast.BoolOp) -> None:
        if not isinstance(node.op, ast.Or):
            return

        for var_name in _duplicated_isinstance_call(node):
            self.add_violation(
                UnmergedIsinstanceCallsViolation(node, text=var_name),
            ) 
Example #24
Source File: definitions.py    From vkbottle with MIT License 5 votes vote down vote up
def or_operator(d: ast.Or):
    return "||" 
Example #25
Source File: markers.py    From syntheticmass with Apache License 2.0 5 votes vote down vote up
def do_boolop(self, node):
        result = self.evaluate(node.values[0])
        is_or = node.op.__class__ is ast.Or
        is_and = node.op.__class__ is ast.And
        assert is_or or is_and
        if (is_and and result) or (is_or and not result):
            for n in node.values[1:]:
                result = self.evaluate(n)
                if (is_or and result) or (is_and and not result):
                    break
        return result 
Example #26
Source File: markers.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def do_boolop(self, node):
        result = self.evaluate(node.values[0])
        is_or = node.op.__class__ is ast.Or
        is_and = node.op.__class__ is ast.And
        assert is_or or is_and
        if (is_and and result) or (is_or and not result):
            for n in node.values[1:]:
                result = self.evaluate(n)
                if (is_or and result) or (is_and and not result):
                    break
        return result 
Example #27
Source File: flatten.py    From kappa with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def visit_BoolOp(self, boolop: ast.BoolOp) -> VisitExprReturnT:
        """
        Due to short-circuiting, desugars boolop into nested if-statements before being flattened.

        For example, this expression::

            x = v1 and v2 and v3

        gets desugared into::

            x = v1
            if x:            # if_test (`x` for `and`, `not x` for `or`)
                x = v2
                if x:
                    x = v3

        This statement block then gets flattened.  The strategy is similar for the `or` operation.
        """
        result_id = self.next_symbol_id()
        result_node = load(result_id)

        if_test: ast.expr
        if isinstance(boolop.op, ast.And):
            if_test = result_node
        elif isinstance(boolop.op, ast.Or):
            if_test = ast.UnaryOp(op=ast.Not(), operand=result_node)
        else:
            assert False, f"BoolOp operation not recognized: {boolop}"

        body: List[ast.stmt] = [assign(result_id, boolop.values[-1])]
        for value in reversed(boolop.values[:-1]):  # Iteratively wrap body in if-statements.
            body = [ast.If(test=if_test, body=body, orelse=[])]
            body.insert(0, assign(result_id, value))

        return load(result_id), self.visit_stmt_list(body) 
Example #28
Source File: topython.py    From pyrser with GNU General Public License v3.0 5 votes vote down vote up
def visit_RepOptional(self, node: parsing.RepOptional) -> ([ast.stmt] or
                                                               ast.expr):
        """Generates python code for an optional clause.

        <code for the clause>
        """
        cl_ast = self.visit(node.pt)
        if isinstance(cl_ast, ast.expr):
            return ast.BoolOp(ast.Or(), [cl_ast, ast.Name('True', ast.Load())])
        self.in_optional += 1
        cl_ast = self.visit(node.pt)
        self.in_optional -= 1
        return cl_ast 
Example #29
Source File: _assertionnew.py    From py with MIT License 5 votes vote down vote up
def visit_BoolOp(self, boolop):
        is_or = isinstance(boolop.op, ast.Or)
        explanations = []
        for operand in boolop.values:
            explanation, result = self.visit(operand)
            explanations.append(explanation)
            if result == is_or:
                break
        name = is_or and " or " or " and "
        explanation = "(" + name.join(explanations) + ")"
        return explanation, result 
Example #30
Source File: markers.py    From recruit with Apache License 2.0 5 votes vote down vote up
def do_boolop(self, node):
        result = self.evaluate(node.values[0])
        is_or = node.op.__class__ is ast.Or
        is_and = node.op.__class__ is ast.And
        assert is_or or is_and
        if (is_and and result) or (is_or and not result):
            for n in node.values[1:]:
                result = self.evaluate(n)
                if (is_or and result) or (is_and and not result):
                    break
        return result