How to use the gast.BinOp function in gast

To help you get started, we’ve selected a few gast examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github serge-sans-paille / pythran / pythran / optimizations / modindex.py View on Github external
break

        if range_ is None:
            return self.generic_visit(node)

        # everything is setup for the transformation!
        new_id = node.left.id + '_m'
        i = 0
        while new_id in self.identifiers:
            new_id = '{}_m{}'.format(node.left.id, i)
            i += 1

        rargs = range_.args.args
        lower = rargs[0] if len(rargs) > 1 else ast.Constant(0, None)
        header = ast.Assign([ast.Name(new_id, ast.Store(), None, None)],
                            ast.BinOp(
                                ast.BinOp(deepcopy(lower),
                                          ast.Sub(),
                                          ast.Constant(1, None)),
                                ast.Mod(),
                                deepcopy(node.right)))
        incr = ast.BinOp(ast.Name(new_id, ast.Load(), None, None),
                         ast.Add(),
                         ast.Constant(1, None))
        step = ast.Assign([ast.Name(new_id, ast.Store(), None, None)],
                          ast.IfExp(
                              ast.Compare(incr,
                                          [ast.Eq()], [deepcopy(node.right)]),
                              ast.Constant(0, None),
                              deepcopy(incr)))

        self.loops_mod.setdefault(loop, []).append((header, step))
github pfnet-research / chainer-compiler / ch2o / ch2o / chainer2onnx.py View on Github external
if isinstance(nast, list):
        # 逐次実行
        for s in nast:
            if is_print_logging(s, env):
                continue
            eval_ast(s, env)
        return None
    elif isinstance(nast, gast.For):
        return eval_for(nast, env)

    elif isinstance(nast, gast.Assign):
        return eval_assign(nast, env)

    elif isinstance(nast, gast.AugAssign):
        # referenceへの代入に対してこれは不正確
        ca = gast.Assign(targets=[nast.target], value=gast.BinOp(
            left=nast.target, op=nast.op, right=nast.value))
        return eval_ast(ca, env)

    elif isinstance(nast, gast.Call):
        return eval_call(nast, env)

    elif isinstance(nast, gast.UnaryOp):
        return eval_unary_op(nast, env)

    elif isinstance(nast, gast.BinOp):
        return eval_binary_op(nast, env)

    elif isinstance(nast, gast.BoolOp):
        # 現在は定数boleanのみ対応
        vs = list(map(lambda x: eval_ast(x, env), nast.values))
        res = new_tensor()
github serge-sans-paille / pythran / pythran / analyses / fixed_size_list.py View on Github external
def is_safe_use(self, use):
        parent = self.ancestors[use.node][-1]

        OK = ast.Subscript, ast.BinOp
        if isinstance(parent, OK):
            return True

        if isinstance(parent, ast.Call):
            n = parent.args.index(use.node)
            return self.is_safe_call(parent.func, n)

        return False
github pfnet-research / chainer-compiler / chainer_compiler / elichika / parser / utils.py View on Github external
def is_expr(node):
    return isinstance(node, gast.BoolOp) \
            or isinstance(node, gast.BinOp) \
            or isinstance(node, gast.UnaryOp) \
            or isinstance(node, gast.Lambda) \
            or isinstance(node, gast.IfExp) \
            or isinstance(node, gast.Dict) \
            or isinstance(node, gast.Set) \
            or isinstance(node, gast.ListComp) \
            or isinstance(node, gast.SetComp) \
            or isinstance(node, gast.DictComp) \
            or isinstance(node, gast.GeneratorExp) \
            or isinstance(node, gast.Await) \
            or isinstance(node, gast.Yield) \
            or isinstance(node, gast.YieldFrom) \
            or isinstance(node, gast.Compare) \
            or isinstance(node, gast.Call) \
            or isinstance(node, gast.Repr) \
            or isinstance(node, gast.Num) \
github pfnet-research / chainer-compiler / chainer_compiler / elichika / parser / typing.py View on Github external
ty_target = self.infer_expr(target)
                ty_val = self.infer_expr(node.value)
                unify(ty_target, ty_val)
                for (var, ty) in zip(target.elts, ty_val.get_tys()):
                    self.tyenv[var.id] = ty
                    self.nodetype[var] = ty
            else:
                assert False

            self.nodetype[node] = TyNone()


        elif isinstance(node, gast.AugAssign):
            # AugAssign(expr target, operator op, expr value)
            if self.tyenv[node.target.id].is_mutable():
                binop = gast.BinOp(node.target, node.op, node.value)
                ty_val = self.infer_expr(binop)
                del self.nodetype[binop]
            else:
                self.tyenv[node.target.id] = deepcopy(self.tyenv[node.target.id])
                binop = gast.BinOp(node.target, node.op, node.value)
                ty_val = self.infer_expr(binop)
                del self.nodetype[binop]
            self.tyenv[node.target.id] = ty_val
            self.nodetype[node.target] = ty_val
            self.nodetype[node] = TyNone()


        elif isinstance(node, gast.For):
            # For(expr target, expr iter, stmt* body, stmt* orelse)
            assert type(node.target) in [gast.Name, gast.Tuple]
github serge-sans-paille / pythran / pythran / transformations / normalize_static_if.py View on Github external
static.append(values.pop())

        after = list(reversed(values))

        test_before = NodeTy(None, None, None)
        if before:
            assert len(before) == 1
            test_before.test = before[0]

        test_static = NodeTy(None, None, None)
        if static:
            test_static.test = static[0]
            if len(static) > 1:
                if after:
                    assert len(after) == 1
                    after = [ast.BinOp(static[1], node.test.op, after[0])]
                else:
                    after = static[1:]

        test_after = NodeTy(None, None, None)
        if after:
            assert len(after) == 1
            test_after.test = after[0]

        if isinstance(node.test.op, ast.BitAnd):
            if after:
                test_after.body = deepcopy(node.body)
                test_after.orelse = deepcopy(node.orelse)
                test_after = W(test_after)
            else:
                test_after = deepcopy(node.body)
github serge-sans-paille / pythran / pythran / optimizations / square.py View on Github external
>>> from pythran import passmanager, backend
    >>> node = ast.parse('a**2')
    >>> pm = passmanager.PassManager("test")
    >>> _, node = pm.apply(Square, node)
    >>> print(pm.dump(backend.Python, node))
    import numpy as __pythran_import_numpy
    __pythran_import_numpy.square(a)
    >>> node = ast.parse('__pythran_import_numpy.power(a,2)')
    >>> pm = passmanager.PassManager("test")
    >>> _, node = pm.apply(Square, node)
    >>> print(pm.dump(backend.Python, node))
    import numpy as __pythran_import_numpy
    __pythran_import_numpy.square(a)
    """

    POW_PATTERN = ast.BinOp(AST_any(), ast.Pow(), ast.Constant(2, None))
    POWER_PATTERN = ast.Call(
        ast.Attribute(ast.Name(mangle('numpy'), ast.Load(), None, None),
                      'power',
                      ast.Load()),
        [AST_any(), ast.Constant(2, None)],
        [])

    def __init__(self):
        Transformation.__init__(self)

    def replace(self, value):
        self.update = self.need_import = True
        module_name = ast.Name(mangle('numpy'), ast.Load(), None, None)
        return ast.Call(ast.Attribute(module_name, 'square', ast.Load()),
                        [value], [])
github serge-sans-paille / pythran / pythran / optimizations / pattern_transform.py View on Github external
class SqrPattern(Pattern):
    # X * X => X ** 2
    pattern = ast.BinOp(left=Placeholder(0),
                        op=ast.Mult(),
                        right=Placeholder(0))

    @staticmethod
    def sub():
        return ast.BinOp(left=Placeholder(0), op=ast.Pow(),
                         right=ast.Constant(2, None))


class StrJoinPattern(Pattern):
    # a + "..." + b => "...".join((a, b))
    pattern = ast.BinOp(left=ast.BinOp(left=Placeholder(0),
                                       op=ast.Add(),
                                       right=ast.Constant(Placeholder(1, str),
                                                          None)),
                        op=ast.Add(),
                        right=Placeholder(2))

    @staticmethod
    def sub():
        return ast.Call(func=ast.Attribute(
            ast.Attribute(
                ast.Name('__builtin__', ast.Load(), None, None),
                'str',
                ast.Load()),
            'join', ast.Load()),
            args=[ast.Constant(Placeholder(1), None),
                  ast.Tuple([Placeholder(0), Placeholder(2)], ast.Load())],
github pfnet-research / chainer-compiler / chainer_compiler / elichika / typing / type_checker.py View on Github external
def infer_expr(self, node):
        if node in self.nodetype.keys():
            return self.nodetype[node]

        self.stack.append(node)

        if self.is_debug:
            pass
            # debug(gast.dump(node))
            # self.dump_stack()
            # self.dump_tyenv()

        if isinstance(node, gast.BoolOp):
            self.nodetype[node] = self.infer_BoolOp(node)
        elif isinstance(node, gast.BinOp):
            self.nodetype[node] = self.infer_BinOp(node)
        elif isinstance(node, gast.UnaryOp):
            self.nodetype[node] = self.infer_UnaryOp(node)
        elif isinstance(node, gast.Dict):
            self.nodetype[node] = self.infer_Dict(node)
        elif isinstance(node, gast.ListComp):
            self.nodetype[node] = self.infer_ListComp(node)
        elif isinstance(node, gast.Compare):
            # Compare(expr left, cmpop* ops, expr* comparators)
            self.nodetype[node] = TyBool()
        elif isinstance(node, gast.Call):
            self.nodetype[node] = self.infer_Call(node)
        elif isinstance(node, gast.Num):
            # Num(object n)
            self.nodetype[node] = type_of_value(node.n)
        elif isinstance(node, gast.Str):
github pfnet-research / chainer-compiler / chainer_compiler / elichika / typing / type_checker.py View on Github external
def infer_AugAssign(self, node):
        # AugAssign(expr target, operator op, expr value)
        binop = gast.BinOp(node.target, node.op, node.value)
        if hasattr(node, 'lineno'):
            setattr(binop, 'lineno', node.lineno)
        ty_val = self.infer_expr(binop)
        ty_target = self.infer_expr(node.target)
        del self.nodetype[binop]
        if ty_target.is_mutable():
            unify(ty_target, ty_val)

        if isinstance(node.target, gast.Name):
            if ty_target.is_mutable():
                self.tyenv[node.target.id] = ty_val
            else:
                self.tyenv[node.target.id] = copy_ty(ty_val)

        if isinstance(node.target, gast.Attribute):
            ty_obj = self.nodetype[node.target.value]

gast

Python AST that abstracts the underlying Python version

BSD-3-Clause
Latest version published 30 days ago

Package Health Score

82 / 100
Full package analysis

Similar packages