Python ast.Sub() Examples

The following are 30 code examples of ast.Sub(). 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: test_ast.py    From CTFCrackTools with GNU General Public License v3.0 6 votes vote down vote up
def test_nodeclasses(self):
        x = ast.BinOp(1, 2, 3, lineno=0)
        self.assertEquals(x.left.n, 1)
        self.assertEquals(int(x.op), 2)
        self.assertEquals(x.right.n, 3)
        self.assertEquals(x.lineno, 0)

        # node raises exception when not given enough arguments
        self.assertRaises(TypeError, ast.BinOp, 1, 2)

        # can set attributes through kwargs too
        x = ast.BinOp(left=1, op=2, right=3, lineno=0)
        self.assertEquals(x.left.n, 1)
        self.assertEquals(int(x.op), 2)
        self.assertEquals(x.right.n, 3)
        self.assertEquals(x.lineno, 0)

        # this used to fail because Sub._fields was None
        x = ast.Sub() 
Example #2
Source File: test_ast.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_nodeclasses(self):
        # IronPyhon performs argument typechecking
        l=ast.Str('A')
        o=ast.Mult()
        r=ast.Num('13')
        x=ast.BinOp(l,o,r,lineno=42)
        self.assertEqual(x.left, l)
        self.assertEqual(x.op, o)
        self.assertEqual(x.right, r)
        self.assertEqual(x.lineno, 42)

        # node raises exception when not given enough arguments
        self.assertRaises(TypeError, ast.BinOp, l, o)

        # can set attributes through kwargs too
        x = ast.BinOp(left=l, op=o, right=r, lineno=42)
        self.assertEqual(x.left, l)
        self.assertEqual(x.op, o)
        self.assertEqual(x.right, r)
        self.assertEqual(x.lineno, 42)

        # this used to fail because Sub._fields was None
        x = ast.Sub() 
Example #3
Source File: _toVHDL.py    From myhdl with GNU Lesser General Public License v2.1 6 votes vote down vote up
def visit_AugAssign(self, node):
        # XXX apparently no signed context required for augmented assigns
        left, op, right = node.target, node.op, node.value
        isFunc = False
        pre, suf = "", ""
        if isinstance(op, (ast.Add, ast.Sub, ast.Mult, ast.Mod, ast.FloorDiv)):
            pre, suf = self.inferBinaryOpCast(node, left, right, op)
        elif isinstance(op, (ast.LShift, ast.RShift)):
            isFunc = True
            pre, suf = self.inferShiftOpCast(node, left, right, op)
        self.visit(left)
        self.write(" := ")
        self.write(pre)
        if isFunc:
            self.write("%s(" % opmap[type(op)])
        self.visit(left)
        if isFunc:
            self.write(", ")
        else:
            self.write(" %s " % opmap[type(op)])
        self.visit(right)
        if isFunc:
            self.write(")")
        self.write(suf)
        self.write(";") 
Example #4
Source File: helper.py    From YAPyPy with MIT License 6 votes vote down vote up
def augassign_rewrite(it: Tokenizer):
    return {
        '+=': ast.Add,
        '-=': ast.Sub,
        '*=': ast.Mult,
        '/=': ast.Div,
        '//=': ast.FloorDiv,
        '@=': ast.MatMult,
        '%=': ast.Mod,
        '&=': ast.BitAnd,
        '|=': ast.BitOr,
        '^=': ast.BitXor,
        '<<=': ast.LShift,
        '>>=': ast.RShift,
        '**=': ast.Pow,
    }[it.value] 
Example #5
Source File: test_ast.py    From CTFCrackTools-V2 with GNU General Public License v3.0 6 votes vote down vote up
def test_nodeclasses(self):
        x = ast.BinOp(1, 2, 3, lineno=0)
        self.assertEquals(x.left.n, 1)
        self.assertEquals(int(x.op), 2)
        self.assertEquals(x.right.n, 3)
        self.assertEquals(x.lineno, 0)

        # node raises exception when not given enough arguments
        self.assertRaises(TypeError, ast.BinOp, 1, 2)

        # can set attributes through kwargs too
        x = ast.BinOp(left=1, op=2, right=3, lineno=0)
        self.assertEquals(x.left.n, 1)
        self.assertEquals(int(x.op), 2)
        self.assertEquals(x.right.n, 3)
        self.assertEquals(x.lineno, 0)

        # this used to fail because Sub._fields was None
        x = ast.Sub() 
Example #6
Source File: test_ast.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_nodeclasses(self):
        # IronPyhon performs argument typechecking
        l=ast.Str('A')
        o=ast.Mult()
        r=ast.Num('13')
        x=ast.BinOp(l,o,r,lineno=42)
        self.assertEqual(x.left, l)
        self.assertEqual(x.op, o)
        self.assertEqual(x.right, r)
        self.assertEqual(x.lineno, 42)

        # node raises exception when not given enough arguments
        self.assertRaises(TypeError, ast.BinOp, l, o)

        # can set attributes through kwargs too
        x = ast.BinOp(left=l, op=o, right=r, lineno=42)
        self.assertEqual(x.left, l)
        self.assertEqual(x.op, o)
        self.assertEqual(x.right, r)
        self.assertEqual(x.lineno, 42)

        # this used to fail because Sub._fields was None
        x = ast.Sub() 
Example #7
Source File: parser.py    From PythonCompiler with GNU General Public License v3.0 6 votes vote down vote up
def parse(self):
        @self.pg.production('program : PRINT OPEN_PAREN expression CLOSE_PAREN SEMI_COLON')
        def program(p):
            return Print(self.builder, self.module, self.printf, p[2])

        @self.pg.production('expression : expression SUM expression')
        @self.pg.production('expression : expression SUB expression')
        def expression(p):
            left = p[0]
            right = p[2]
            operator = p[1]
            if operator.gettokentype() == 'SUM':
                return Sum(self.builder, self.module, left, right)
            elif operator.gettokentype() == 'SUB':
                return Sub(self.builder, self.module, left, right)

        @self.pg.production('expression : NUMBER')
        def number(p):
            return Number(self.builder, self.module, p[0].value)

        @self.pg.error
        def error_handle(token):
            raise ValueError(token) 
Example #8
Source File: test_ast.py    From medicare-demo with Apache License 2.0 6 votes vote down vote up
def test_nodeclasses(self):
        x = ast.BinOp(1, 2, 3, lineno=0)
        self.assertEquals(x.left.n, 1)
        self.assertEquals(int(x.op), 2)
        self.assertEquals(x.right.n, 3)
        self.assertEquals(x.lineno, 0)

        # node raises exception when not given enough arguments
        self.assertRaises(TypeError, ast.BinOp, 1, 2)

        # can set attributes through kwargs too
        x = ast.BinOp(left=1, op=2, right=3, lineno=0)
        self.assertEquals(x.left.n, 1)
        self.assertEquals(int(x.op), 2)
        self.assertEquals(x.right.n, 3)
        self.assertEquals(x.lineno, 0)

        # this used to fail because Sub._fields was None
        x = ast.Sub() 
Example #9
Source File: definitions.py    From vkbottle with MIT License 5 votes vote down vote up
def sub_operator(d: ast.Sub):
    return "-" 
Example #10
Source File: ast_transformer.py    From web_develop with GNU General Public License v3.0 5 votes vote down vote up
def visit_Add(self, node):
        node = ast.Sub()
        return node 
Example #11
Source File: ast_visitor.py    From web_develop with GNU General Public License v3.0 5 votes vote down vote up
def visit_Add(self, node):
        node = ast.Sub()
        return node 
Example #12
Source File: parser.py    From vecpy with MIT License 5 votes vote down vote up
def binop(self, block, node, var=None):
    if var is None:
      var = self.add_variable(None)
    left = self.expression(block, node.left)
    right = self.expression(block, node.right)
    if isinstance(node.op, ast.Add):
      op = Operator.add
    elif isinstance(node.op, ast.Sub):
      op = Operator.subtract
    elif isinstance(node.op, ast.Mult):
      op = Operator.multiply
    elif isinstance(node.op, ast.Div):
      op = Operator.divide
    elif isinstance(node.op, ast.FloorDiv):
      op = Operator.divide_int
    elif isinstance(node.op, ast.Mod):
      op = Operator.mod
    elif isinstance(node.op, ast.Pow):
      op = Operator.pow
    elif isinstance(node.op, ast.BitAnd):
      op = Operator.bit_and
    elif isinstance(node.op, ast.BitOr):
      op = Operator.bit_or
    elif isinstance(node.op, ast.BitXor):
      op = Operator.bit_xor
    elif isinstance(node.op, ast.LShift):
      op = Operator.shift_left
    elif isinstance(node.op, ast.RShift):
      op = Operator.shift_right
    else:
      raise Exception('Unexpected BinOp (%s)'%(node.op.__class__))
    operation = BinaryOperation(left, op, right)
    assignment = Assignment(var, operation)
    block.add(assignment)
    return var

  #Parses a unary uperation (AST UnaryOp) 
Example #13
Source File: test_ast.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_no_fields(self):
        # this used to fail because Sub._fields was None
        x = ast.Sub()
        self.assertEqual(x._fields, ()) 
Example #14
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_augassign_2(p):
    '''augassign : MINEQUAL'''
    #                     1
    p[0] = ast.Sub(rule=inspect.currentframe().f_code.co_name, **p[1][1]) 
Example #15
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_arith_expr_star_2(p):
    '''arith_expr_star : MINUS term'''
    #                        1    2
    p[0] = [ast.Sub(rule=inspect.currentframe().f_code.co_name, **p[1][1]), p[2]] 
Example #16
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_arith_expr_star_4(p):
    '''arith_expr_star : arith_expr_star MINUS term'''
    #                                  1     2    3
    p[0] = p[1] + [ast.Sub(rule=inspect.currentframe().f_code.co_name, **p[2][1]), p[3]]

# term: factor (('*'|'/'|'%'|'//') factor)* 
Example #17
Source File: test_ast.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_no_fields(self):
        # this used to fail because Sub._fields was None
        x = ast.Sub()
        self.assertEqual(x._fields, ()) 
Example #18
Source File: test_ast.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_no_fields(self):
        # this used to fail because Sub._fields was None
        x = ast.Sub()
        self.assertEqual(x._fields, ()) 
Example #19
Source File: common.py    From fdroidserver with GNU Affero General Public License v3.0 5 votes vote down vote up
def calculate_math_string(expr):
    ops = {
        ast.Add: operator.add,
        ast.Mult: operator.mul,
        ast.Sub: operator.sub,
        ast.USub: operator.neg,
    }

    def execute_ast(node):
        if isinstance(node, ast.Num):  # <number>
            return node.n
        elif isinstance(node, ast.BinOp):  # <left> <operator> <right>
            return ops[type(node.op)](execute_ast(node.left),
                                      execute_ast(node.right))
        elif isinstance(node, ast.UnaryOp):  # <operator> <operand> e.g., -1
            return ops[type(node.op)](ast.literal_eval(node.operand))
        else:
            raise SyntaxError(node)

    try:
        if '#' in expr:
            raise SyntaxError('no comments allowed')
        return execute_ast(ast.parse(expr, mode='eval').body)
    except SyntaxError:
        raise SyntaxError("could not parse expression '{expr}', "
                          "only basic math operations are allowed (+, -, *)"
                          .format(expr=expr)) 
Example #20
Source File: subscripts.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def _check_len_call(self, node: ast.Subscript) -> None:
        is_len_call = (
            isinstance(node.slice, ast.Index) and
            isinstance(node.slice.value, ast.BinOp) and
            isinstance(node.slice.value.op, ast.Sub) and
            self._is_wrong_len(
                node.slice.value,
                source.node_to_string(node.value),
            )
        )

        if is_len_call:
            self.add_violation(
                refactoring.ImplicitNegativeIndexViolation(node),
            ) 
Example #21
Source File: operators.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def _check_negation(self, op: ast.operator, right: ast.AST) -> None:
        is_double_minus = (
            isinstance(op, (ast.Add, ast.Sub)) and
            isinstance(right, ast.UnaryOp) and
            isinstance(right.op, ast.USub)
        )
        if is_double_minus:
            self.add_violation(
                consistency.OperationSignNegationViolation(right),
            ) 
Example #22
Source File: safe_eval.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def literal_eval_with_names(  # noqa: WPS231
    node: Optional[ast.AST],
) -> Any:
    """
    Safely evaluate constants and ``ast.Name`` nodes.

    We need this function to tell
    that ``[name]`` and ``[name]`` are the same nodes.

    Copied from the CPython's source code.
    Modified to treat ``ast.Name`` nodes as constants.

    See: :py:`ast.literal_eval` source.

    We intentionally ignore complexity violation here,
    becase we try to stay as close to the original source as possible.
    """
    binary_operators = (ast.Add, ast.Sub)
    if isinstance(node, (Constant, ast.NameConstant)):
        return node.value
    elif isinstance(node, (ast.Str, ast.Bytes, ast.Num)):  # pragma: py-gte-38
        # We wrap strings to tell the difference between strings and names:
        return node.n if isinstance(node, ast.Num) else '"{0!r}"'.format(node.s)
    elif isinstance(node, (ast.Tuple, ast.List, ast.Set, ast.Dict)):
        return _convert_iterable(node)
    elif isinstance(node, ast.BinOp) and isinstance(node.op, binary_operators):
        maybe_complex = _convert_complex(node)
        if maybe_complex is not None:
            return maybe_complex
    return _convert_signed_num(node) 
Example #23
Source File: converter.py    From Airtight with MIT License 5 votes vote down vote up
def convert_subscript(self, value, slice, ctx, context):
        if isinstance(slice, ast.Index):
            return hm_ast.Multi_Apply(
                hm_ast.Ident('a' + self.OPERATOR_MAGIC_FUNCTIONS[type(slice)]), [
                self.convert_node(value, context),
                self.convert_node(slice.value)])
        else:
            return hm_ast.Multi_Apply(
                hm_ast.Ident('a' + self.OPERATOR_MAGIC_FUNCTIONS[type(slice)]), [
                self.convert_node(value, context),
                self.convert_node(slice.lower) if slice.lower else hm_ast.anInteger(0),
                self.convert_node(slice.upper) if slice.upper else hm_ast.Multi_Apply(
                    self.OPERATOR_MAGIC_FUNCTIONS[ast.Sub], [
                    hm_ast.Apply(hm_ast.Ident('len'), self.convert_node(value, context)),
                    hm_ast.anInteger(1)])]) 
Example #24
Source File: _recompute.py    From icontract with MIT License 5 votes vote down vote up
def visit_BinOp(self, node: ast.BinOp) -> Any:
        """Recursively visit the left and right operand, respectively, and apply the operation on the results."""
        # pylint: disable=too-many-branches
        left = self.visit(node=node.left)
        right = self.visit(node=node.right)

        if isinstance(node.op, ast.Add):
            result = left + right
        elif isinstance(node.op, ast.Sub):
            result = left - right
        elif isinstance(node.op, ast.Mult):
            result = left * right
        elif isinstance(node.op, ast.Div):
            result = left / right
        elif isinstance(node.op, ast.FloorDiv):
            result = left // right
        elif isinstance(node.op, ast.Mod):
            result = left % right
        elif isinstance(node.op, ast.Pow):
            result = left**right
        elif isinstance(node.op, ast.LShift):
            result = left << right
        elif isinstance(node.op, ast.RShift):
            result = left >> right
        elif isinstance(node.op, ast.BitOr):
            result = left | right
        elif isinstance(node.op, ast.BitXor):
            result = left ^ right
        elif isinstance(node.op, ast.BitAnd):
            result = left & right
        elif isinstance(node.op, ast.MatMult):
            result = left @ right
        else:
            raise NotImplementedError("Unhandled op of {}: {}".format(node, node.op))

        self.recomputed_values[node] = result
        return result 
Example #25
Source File: expressions.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def stringify_operation(op: Any) -> str:
        if isinstance(op, ast.Add):
            return '+'
        if isinstance(op, ast.Sub):
            return '-'
        if isinstance(op, ast.Mult):
            return '*'
        if isinstance(op, ast.Div) or isinstance(op, ast.FloorDiv):
            return '/'
        return str(op) 
Example #26
Source File: test_ast.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_no_fields(self):
        # this used to fail because Sub._fields was None
        x = ast.Sub()
        self.assertEqual(x._fields, ()) 
Example #27
Source File: _toVerilog.py    From myhdl with GNU Lesser General Public License v2.1 5 votes vote down vote up
def visit_BinOp(self, node):
        self.visit(node.left)
        self.visit(node.right)
        node.signed = node.left.signed or node.right.signed
        # special treatement of subtraction unless in a top-level rhs
        if isinstance(node.op, ast.Sub) and not hasattr(node, 'isRhs'):
            node.signed = True 
Example #28
Source File: BehavioralRTLIRGenL2Pass.py    From pymtl3 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__( s, component ):
    super().__init__( component )
    s.loop_var_env = set()
    s.tmp_var_env = set()

    # opmap maps an ast operator to its RTLIR counterpart.
    s.opmap = {
      # Bool operators
      # Note: we do not support boolean operators because Python does
      # not allow overloading And and Or operators. Using them in
      # expressions might lead to inconsistent semantics.
      # ast.And    : bir.And(),       ast.Or     : bir.Or(),
      # Unary operators
      # Note: ast.Not is disallowed because it is a boolean operator
      # ast.Not    : bir.Not(),
      ast.Invert : bir.Invert(),
      ast.UAdd   : bir.UAdd(),      ast.USub   : bir.USub(),
      # Binary operators
      ast.Add    : bir.Add(),       ast.Sub    : bir.Sub(),
      ast.Mult   : bir.Mult(),      ast.Div    : bir.Div(),
      ast.Mod    : bir.Mod(),       ast.Pow    : bir.Pow(),
      ast.LShift : bir.ShiftLeft(), ast.RShift : bir.ShiftRightLogic(),
      ast.BitOr  : bir.BitOr(),     ast.BitAnd : bir.BitAnd(),
      ast.BitXor : bir.BitXor(),
      # Compare bir.bir.operators
      ast.Eq     : bir.Eq(),        ast.NotEq  : bir.NotEq(),
      ast.Lt     : bir.Lt(),        ast.LtE    : bir.LtE(),
      ast.Gt     : bir.Gt(),        ast.GtE    : bir.GtE()
    }

  # Override 
Example #29
Source File: test_ast.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_no_fields(self):
        # this used to fail because Sub._fields was None
        x = ast.Sub()
        self.assertEqual(x._fields, ()) 
Example #30
Source File: test_ast.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_no_fields(self):
        # this used to fail because Sub._fields was None
        x = ast.Sub()
        self.assertEqual(x._fields, ())