Python ast.And() Examples

The following are 30 code examples of ast.And(). 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: expr.py    From recruit with Apache License 2.0 6 votes vote down vote up
def visit_Compare(self, node, **kwargs):
        ops = node.ops
        comps = node.comparators

        # base case: we have something like a CMP b
        if len(comps) == 1:
            op = self.translate_In(ops[0])
            binop = ast.BinOp(op=op, left=node.left, right=comps[0])
            return self.visit(binop)

        # recursive case: we have a chained comparison, a CMP b CMP c, etc.
        left = node.left
        values = []
        for op, comp in zip(ops, comps):
            new_node = self.visit(ast.Compare(comparators=[comp], left=left,
                                              ops=[self.translate_In(op)]))
            left = comp
            values.append(new_node)
        return self.visit(ast.BoolOp(op=ast.And(), values=values)) 
Example #2
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 #3
Source File: expr.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
def visit_Compare(self, node, **kwargs):
        ops = node.ops
        comps = node.comparators

        # base case: we have something like a CMP b
        if len(comps) == 1:
            op = self.translate_In(ops[0])
            binop = ast.BinOp(op=op, left=node.left, right=comps[0])
            return self.visit(binop)

        # recursive case: we have a chained comparison, a CMP b CMP c, etc.
        left = node.left
        values = []
        for op, comp in zip(ops, comps):
            new_node = self.visit(ast.Compare(comparators=[comp], left=left,
                                              ops=[self.translate_In(op)]))
            left = comp
            values.append(new_node)
        return self.visit(ast.BoolOp(op=ast.And(), values=values)) 
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: CodeGenerate_By_Ast.py    From ontology-python-compiler with GNU Lesser General Public License v3.0 6 votes vote down vote up
def visit_BoolOp(self, node):
        len_t = len(node.values)
        assert(len_t >= 2)
        End_target_label = self.codegencontext.NewLabel()
        End_target_postion = End_target_label.to_bytes(2, 'little', signed=True)

        for i in range(len_t):
            self.visit(node.values[i])
            if i != (len_t - 1):
                if (type(node.op).__name__ == 'Or'):
                    self.codegencontext.tokenizer.Emit_Token(VMOp.DUP, node)
                    self.codegencontext.tokenizer.Emit_Token(VMOp.JMPIF, node, End_target_postion)
                    self.codegencontext.tokenizer.Emit_Token(VMOp.DROP, node)
                elif (type(node.op).__name__ == 'And'):
                    self.codegencontext.tokenizer.Emit_Token(VMOp.DUP, node)
                    self.codegencontext.tokenizer.Emit_Token(VMOp.JMPIFNOT, node, End_target_postion)
                    self.codegencontext.tokenizer.Emit_Token(VMOp.DROP, node)
                else:
                    assert(False)

        self.codegencontext.SetLabel(End_target_label, self.codegencontext.pc + 1) 
Example #6
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 #7
Source File: yacc.py    From yaksok with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def p_logic_and_expr(t):
    '''logic_and_expr : logic_and_expr AND logic_expr
                      | logic_expr'''
    if len(t) == 4:
        if isinstance(t[1], ast.BoolOp) and isinstance(t[1].op, ast.And):
            t[0] = t[1]
            t[0].values.append(t[3])
        else:
            and_ast = ast.And()
            and_ast.lineno = t.lineno(2)
            and_ast.col_offset = -1 # XXX
            t[0] = ast.BoolOp(and_ast, [t[1], t[3]])
            t[0].lineno = t.lineno(2)
            t[0].col_offset = -1 # XXX
    else:
        t[0] = t[1] 
Example #8
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 #9
Source File: expr.py    From elasticintel with GNU General Public License v3.0 6 votes vote down vote up
def visit_Compare(self, node, **kwargs):
        ops = node.ops
        comps = node.comparators

        # base case: we have something like a CMP b
        if len(comps) == 1:
            op = self.translate_In(ops[0])
            binop = ast.BinOp(op=op, left=node.left, right=comps[0])
            return self.visit(binop)

        # recursive case: we have a chained comparison, a CMP b CMP c, etc.
        left = node.left
        values = []
        for op, comp in zip(ops, comps):
            new_node = self.visit(ast.Compare(comparators=[comp], left=left,
                                              ops=[self.translate_In(op)]))
            left = comp
            values.append(new_node)
        return self.visit(ast.BoolOp(op=ast.And(), values=values)) 
Example #10
Source File: expr.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def visit_Compare(self, node, **kwargs):
        ops = node.ops
        comps = node.comparators

        # base case: we have something like a CMP b
        if len(comps) == 1:
            op = self.translate_In(ops[0])
            binop = ast.BinOp(op=op, left=node.left, right=comps[0])
            return self.visit(binop)

        # recursive case: we have a chained comparison, a CMP b CMP c, etc.
        left = node.left
        values = []
        for op, comp in zip(ops, comps):
            new_node = self.visit(ast.Compare(comparators=[comp], left=left,
                                              ops=[self.translate_In(op)]))
            left = comp
            values.append(new_node)
        return self.visit(ast.BoolOp(op=ast.And(), values=values)) 
Example #11
Source File: SimulatorExpressionParser.py    From urh with GNU General Public License v3.0 6 votes vote down vote up
def evaluate_node(self, node):
        if isinstance(node, ast.BinOp):
            return self.operators[type(node.op)](self.evaluate_node(node.left),
                                                 self.evaluate_node(node.right))
        elif isinstance(node, ast.UnaryOp):
            return self.operators[type(node.op)](self.evaluate_node(node.operand))
        elif isinstance(node, ast.Compare):
            to_string = isinstance(node.comparators[0], ast.Str)

            return self.operators[type(node.ops[0])](self.evaluate_attribute_node(node.left, to_string),
                                                     self.evaluate_node(node.comparators[0]))
        elif isinstance(node, ast.BoolOp):
            func = all if isinstance(node.op, ast.And) else any
            return func(self.evaluate_node(value) for value in node.values)
        elif isinstance(node, ast.Str):
            return node.s
        elif isinstance(node, ast.Attribute):
            return self.evaluate_attribute_node(node)
        elif isinstance(node, ast.Num):
            return node.n
        else:
            logger.error("Error during parsing") 
Example #12
Source File: expr.py    From Computable with MIT License 6 votes vote down vote up
def visit_Compare(self, node, **kwargs):
        ops = node.ops
        comps = node.comparators

        # base case: we have something like a CMP b
        if len(comps) == 1:
            op = self.translate_In(ops[0])
            binop = ast.BinOp(op=op, left=node.left, right=comps[0])
            return self.visit(binop)

        # recursive case: we have a chained comparison, a CMP b CMP c, etc.
        left = node.left
        values = []
        for op, comp in zip(ops, comps):
            new_node = self.visit(ast.Compare(comparators=[comp], left=left,
                                              ops=[self.translate_In(op)]))
            left = comp
            values.append(new_node)
        return self.visit(ast.BoolOp(op=ast.And(), values=values)) 
Example #13
Source File: expr.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def visit_Compare(self, node, **kwargs):
        ops = node.ops
        comps = node.comparators

        # base case: we have something like a CMP b
        if len(comps) == 1:
            op = self.translate_In(ops[0])
            binop = ast.BinOp(op=op, left=node.left, right=comps[0])
            return self.visit(binop)

        # recursive case: we have a chained comparison, a CMP b CMP c, etc.
        left = node.left
        values = []
        for op, comp in zip(ops, comps):
            new_node = self.visit(ast.Compare(comparators=[comp], left=left,
                                              ops=[self.translate_In(op)]))
            left = comp
            values.append(new_node)
        return self.visit(ast.BoolOp(op=ast.And(), values=values)) 
Example #14
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 #15
Source File: normalizer.py    From bigcode-tools with MIT License 6 votes vote down vote up
def normalize_compare(node):
    """Rewrites a compare expression to a `and` expression
    1 < 2 < 3 > 0
    1 < 2 and 2 < 3 and 3 > 0"""
    and_values = []
    left = node.left
    for (op, val) in zip(node.ops, node.comparators):
        comp = ast.Compare(ops=[op],
                           left=left,
                           comparators=[val],
                           lineno=node.lineno,
                           col_offset=node.col_offset)
        and_values.append(comp)
        left = val
    return ast.BoolOp(op=ast.And(),
                      values=and_values,
                      lineno=node.lineno,
                      col_offset=node.col_offset) 
Example #16
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 #17
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 #18
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 #19
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_and_test_2(p):
    '''and_test : not_test and_test_star'''
    #                    1             2
    theand = ast.And(rule=inspect.currentframe().f_code.co_name)
    inherit_lineno(theand, p[2][0])
    p[0] = ast.BoolOp(theand, [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: conftest.py    From mutatest with MIT License 5 votes vote down vote up
def boolop_expected_loc():
    """Expected location index of the boolop fixture"""
    # Py 3.7 vs 3.8
    end_lineno = None if sys.version_info < (3, 8) else 2
    end_col_offset = None if sys.version_info < (3, 8) else 18
    return LocIndex(
        ast_class="BoolOp",
        lineno=2,
        col_offset=11,
        op_type=ast.And,
        end_lineno=end_lineno,
        end_col_offset=end_col_offset,
    ) 
Example #22
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 #23
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 #24
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 #25
Source File: definitions.py    From vkbottle with MIT License 5 votes vote down vote up
def and_operator(d: ast.And):
    return "&&" 
Example #26
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 #27
Source File: conditions.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def _check_implicit_complex_compare(self, node: ast.BoolOp) -> None:
        if not isinstance(node.op, ast.And):
            return

        if not CompareBounds(node).is_valid():
            self.add_violation(ImplicitComplexCompareViolation(node)) 
Example #28
Source File: utils.py    From vulture with MIT License 5 votes vote down vote up
def _safe_eval(node, default):
    """
    Safely evaluate the Boolean expression under the given AST node.

    Substitute `default` for all sub-expressions that cannot be
    evaluated (because variables or functions are undefined).

    We could use eval() to evaluate more sub-expressions. However, this
    function is not safe for arbitrary Python code. Even after
    overwriting the "__builtins__" dictionary, the original dictionary
    can be restored
    (https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html).

    """
    if isinstance(node, ast.BoolOp):
        results = [_safe_eval(value, default) for value in node.values]
        if isinstance(node.op, ast.And):
            return all(results)
        else:
            return any(results)
    elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
        return not _safe_eval(node.operand, not default)
    else:
        try:
            return ast.literal_eval(node)
        except ValueError:
            return default 
Example #29
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 #30
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