當前位置: 首頁>>代碼示例>>Python>>正文


Python c_ast.BinaryOp方法代碼示例

本文整理匯總了Python中pycparser.c_ast.BinaryOp方法的典型用法代碼示例。如果您正苦於以下問題:Python c_ast.BinaryOp方法的具體用法?Python c_ast.BinaryOp怎麽用?Python c_ast.BinaryOp使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在pycparser.c_ast的用法示例。


在下文中一共展示了c_ast.BinaryOp方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_scalar_children

# 需要導入模塊: from pycparser import c_ast [as 別名]
# 或者: from pycparser.c_ast import BinaryOp [as 別名]
def test_scalar_children(self):
        b1 = c_ast.BinaryOp(
            op='+',
            left=c_ast.Constant(type='int', value='6'),
            right=c_ast.ID(name='joe'))

        cv = self.ConstantVisitor()
        cv.visit(b1)

        self.assertEqual(cv.values, ['6'])

        b2 = c_ast.BinaryOp(
            op='*',
            left=c_ast.Constant(type='int', value='111'),
            right=b1)

        b3 = c_ast.BinaryOp(
            op='^',
            left=b2,
            right=b1)

        cv = self.ConstantVisitor()
        cv.visit(b3)

        self.assertEqual(cv.values, ['111', '6', '6']) 
開發者ID:johncsnyder,項目名稱:SwiftKitten,代碼行數:27,代碼來源:test_c_ast.py

示例2: tests_list_children

# 需要導入模塊: from pycparser import c_ast [as 別名]
# 或者: from pycparser.c_ast import BinaryOp [as 別名]
def tests_list_children(self):
        c1 = c_ast.Constant(type='float', value='5.6')
        c2 = c_ast.Constant(type='char', value='t')

        b1 = c_ast.BinaryOp(
            op='+',
            left=c1,
            right=c2)

        b2 = c_ast.BinaryOp(
            op='-',
            left=b1,
            right=c2)

        comp = c_ast.Compound(
            block_items=[b1, b2, c1, c2])

        cv = self.ConstantVisitor()
        cv.visit(comp)

        self.assertEqual(cv.values,
            ['5.6', 't', '5.6', 't', 't', '5.6', 't']) 
開發者ID:johncsnyder,項目名稱:SwiftKitten,代碼行數:24,代碼來源:test_c_ast.py

示例3: parse_constant_int

# 需要導入模塊: from pycparser import c_ast [as 別名]
# 或者: from pycparser.c_ast import BinaryOp [as 別名]
def parse_constant_int(expr: "ca.Expression") -> int:
    if isinstance(expr, ca.Constant):
        try:
            return int(expr.value.rstrip("lLuU"), 0)
        except ValueError:
            raise DecompFailure(f"Failed to parse {to_c(expr)} as an int literal")
    if isinstance(expr, ca.BinaryOp):
        lhs = parse_constant_int(expr.left)
        rhs = parse_constant_int(expr.right)
        if expr.op == "+":
            return lhs + rhs
        if expr.op == "-":
            return lhs - rhs
        if expr.op == "*":
            return lhs * rhs
        if expr.op == "<<":
            return lhs << rhs
        if expr.op == ">>":
            return lhs >> rhs
    raise DecompFailure(
        f"Failed to evaluate expression {to_c(expr)} at compile time; only simple arithmetic is supported for now"
    ) 
開發者ID:matt-kempster,項目名稱:mips_to_c,代碼行數:24,代碼來源:c_types.py

示例4: transform_multidim_to_1d_decl

# 需要導入模塊: from pycparser import c_ast [as 別名]
# 或者: from pycparser.c_ast import BinaryOp [as 別名]
def transform_multidim_to_1d_decl(decl):
    """
    Transform ast of multidimensional declaration to a single dimension declaration.

    In-place operation!

    Returns name and dimensions of array (to be used with transform_multidim_to_1d_ref())
    """
    dims = []
    type_ = decl.type
    while type(type_) is c_ast.ArrayDecl:
        dims.append(type_.dim)
        type_ = type_.type

    if dims:
        # Multidimensional array
        decl.type.dim = reduce(lambda l, r: c_ast.BinaryOp('*', l, r), dims)
        decl.type.type = type_

    return decl.name, dims 
開發者ID:RRZE-HPC,項目名稱:kerncraft,代碼行數:22,代碼來源:kernel.py

示例5: transform_multidim_to_1d_ref

# 需要導入模塊: from pycparser import c_ast [as 別名]
# 或者: from pycparser.c_ast import BinaryOp [as 別名]
def transform_multidim_to_1d_ref(aref, dimension_dict):
    """
    Transform ast of multidimensional reference to a single dimension reference.

    In-place operation!
    """
    dims = []
    name = aref
    while type(name) is c_ast.ArrayRef:
        dims.append(name.subscript)
        name = name.name

    subscript_list = []
    for i, d in enumerate(dims):
        if i == 0:
            subscript_list.append(d)
        else:
            subscript_list.append(c_ast.BinaryOp('*', d, reduce(
                lambda l, r: c_ast.BinaryOp('*', l, r),
                dimension_dict[name.name][-1:-i-1:-1])))

    aref.subscript = reduce(
        lambda l, r: c_ast.BinaryOp('+', l, r), subscript_list)
    aref.name = name 
開發者ID:RRZE-HPC,項目名稱:kerncraft,代碼行數:26,代碼來源:kernel.py

示例6: conv_ast_to_sym

# 需要導入模塊: from pycparser import c_ast [as 別名]
# 或者: from pycparser.c_ast import BinaryOp [as 別名]
def conv_ast_to_sym(self, math_ast):
        """
        Convert mathematical expressions to a sympy representation.

        May only contain paranthesis, addition, subtraction and multiplication from AST.
        """
        if type(math_ast) is c_ast.ID:
            return symbol_pos_int(math_ast.name)
        elif type(math_ast) is c_ast.Constant:
            return sympy.Integer(math_ast.value)
        else:  # elif type(dim) is c_ast.BinaryOp:
            op = {
                '*': operator.mul,
                '+': operator.add,
                '-': operator.sub
            }

            return op[math_ast.op](
                self.conv_ast_to_sym(math_ast.left),
                self.conv_ast_to_sym(math_ast.right)) 
開發者ID:RRZE-HPC,項目名稱:kerncraft,代碼行數:22,代碼來源:kernel.py

示例7: test_BinaryOp

# 需要導入模塊: from pycparser import c_ast [as 別名]
# 或者: from pycparser.c_ast import BinaryOp [as 別名]
def test_BinaryOp(self):
        b1 = c_ast.BinaryOp(
            op='+',
            left=c_ast.Constant(type='int', value='6'),
            right=c_ast.ID(name='joe'))

        self.failUnless(isinstance(b1.left, c_ast.Constant))
        self.assertEqual(b1.left.type, 'int')
        self.assertEqual(b1.left.value, '6')

        self.failUnless(isinstance(b1.right, c_ast.ID))
        self.assertEqual(b1.right.name, 'joe') 
開發者ID:johncsnyder,項目名稱:SwiftKitten,代碼行數:14,代碼來源:test_c_ast.py

示例8: render_const

# 需要導入模塊: from pycparser import c_ast [as 別名]
# 或者: from pycparser.c_ast import BinaryOp [as 別名]
def render_const(value):
    if isinstance(value, c_ast.Constant):
        return value.value
    elif isinstance(value, c_ast.BinaryOp):
        return '{} {} {}'.format(
            render_const(value.left), value.op, render_const(value.right))
    else:
        die('unexpected constant value: {!r}'.format(value)) 
開發者ID:pinterest,項目名稱:ptracer,代碼行數:10,代碼來源:extract_ptrace_constants.py

示例9: fold_const_expr

# 需要導入模塊: from pycparser import c_ast [as 別名]
# 或者: from pycparser.c_ast import BinaryOp [as 別名]
def fold_const_expr(expr, typedefs):
    if isinstance(expr, c_ast.BinaryOp):
        left = fold_const_expr(expr.left, typedefs)
        right = fold_const_expr(expr.right, typedefs)
        oper = _binopmap.get(expr.op)
        if oper is None:
            die('cannot fold binop with {!r}'.format(expr.op))

        result = oper(left, right)

    elif isinstance(expr, c_ast.UnaryOp):
        operand = fold_const_expr(expr.expr, typedefs)
        oper = _unopmap.get(expr.op)

        if oper is None:
            die('cannot fold unop with {!r}'.format(expr.op))

        result = oper(operand)

    elif isinstance(expr, c_ast.Constant):
        lit_type = _literalmap.get(expr.type)
        if lit_type is None:
            die('unexpected constant type: {!r}'.format(expr.type))
        result = lit_type(expr.value)

    elif isinstance(expr, c_ast.Typename):
        # sizeof operand
        result = get_final_ctypes_type(expr.type, typedefs)
        _, _, typ = result.rpartition('.')
        result = getattr(ctypes, typ)

    else:
        die('cannot fold {!r} expr'.format(expr))

    return result 
開發者ID:pinterest,項目名稱:ptracer,代碼行數:37,代碼來源:extract_ptrace_constants.py

示例10: visit_BinaryOp

# 需要導入模塊: from pycparser import c_ast [as 別名]
# 或者: from pycparser.c_ast import BinaryOp [as 別名]
def visit_BinaryOp(self, node):
        '''
        BinaryOp - binary operation
        Attrs: op, left, right
        '''

        return Op(node.op, self.visit_expr(node.left),
                  self.visit_expr(node.right), line=node.coord.line) 
開發者ID:iradicek,項目名稱:clara,代碼行數:10,代碼來源:c_parser.py

示例11: transform_array_decl_to_malloc

# 需要導入模塊: from pycparser import c_ast [as 別名]
# 或者: from pycparser.c_ast import BinaryOp [as 別名]
def transform_array_decl_to_malloc(decl, with_init=True):
    """
    Transform ast of "type var_name[N]" to "type* var_name = aligned_malloc(sizeof(type)*N, 32)"

    In-place operation.

    :param with_init: if False, ommit malloc
    """
    if type(decl.type) is not c_ast.ArrayDecl:
        # Not an array declaration, can be ignored
        return

    type_ = c_ast.PtrDecl([], decl.type.type)
    if with_init:
        decl.init = c_ast.FuncCall(
            c_ast.ID('aligned_malloc'),
            c_ast.ExprList([
                c_ast.BinaryOp(
                    '*',
                    c_ast.UnaryOp(
                        'sizeof',
                        c_ast.Typename(None, [], c_ast.TypeDecl(
                            None, [], decl.type.type.type))),
                    decl.type.dim),
                c_ast.Constant('int', '32')]))
    decl.type = type_ 
開發者ID:RRZE-HPC,項目名稱:kerncraft,代碼行數:28,代碼來源:kernel.py

示例12: _get_offsets

# 需要導入模塊: from pycparser import c_ast [as 別名]
# 或者: from pycparser.c_ast import BinaryOp [as 別名]
def _get_offsets(self, aref, dim=0):
        """
        Return a tuple of offsets of an ArrayRef object in all dimensions.

        The index order is right to left (c-code order).
        e.g. c[i+1][j-2] -> (j-2, i+1)

        If aref is actually a c_ast.ID, None will be returned.
        """
        if isinstance(aref, c_ast.ID):
            return None

        # Check for restrictions
        assert type(aref.name) in [c_ast.ArrayRef, c_ast.ID], \
            "array references must only be used with variables or other array references"
        assert type(aref.subscript) in [c_ast.ID, c_ast.Constant, c_ast.BinaryOp], \
            'array subscript must only contain variables or binary operations'

        # Convert subscript to sympy and append
        idxs = [self.conv_ast_to_sym(aref.subscript)]

        # Check for more indices (multi-dimensional access)
        if type(aref.name) is c_ast.ArrayRef:
            idxs += self._get_offsets(aref.name, dim=dim+1)

        # Reverse to preserver order (the subscripts in the AST are traversed backwards)
        if dim == 0:
            idxs.reverse()

        return tuple(idxs) 
開發者ID:RRZE-HPC,項目名稱:kerncraft,代碼行數:32,代碼來源:kernel.py

示例13: ast_eval_int

# 需要導入模塊: from pycparser import c_ast [as 別名]
# 或者: from pycparser.c_ast import BinaryOp [as 別名]
def ast_eval_int(self, ast):
        """Eval a C ast object integer

        @ast: parsed pycparser.c_ast object
        """

        if isinstance(ast, c_ast.BinaryOp):
            left = self.ast_eval_int(ast.left)
            right = self.ast_eval_int(ast.right)
            is_pure_int = (isinstance(left, int) and
                           isinstance(right, int))

            if is_pure_int:
                if ast.op == '*':
                    result = left * right
                elif ast.op == '/':
                    assert left % right == 0
                    result = left // right
                elif ast.op == '+':
                    result = left + right
                elif ast.op == '-':
                    result = left - right
                elif ast.op == '<<':
                    result = left << right
                elif ast.op == '>>':
                    result = left >> right
                else:
                    raise NotImplementedError("Not implemented!")
            else:
                result = CTypeOp(ast.op, left, right)

        elif isinstance(ast, c_ast.UnaryOp):
            if ast.op == 'sizeof' and isinstance(ast.expr, c_ast.Typename):
                subobj = self.ast_to_typeid(ast.expr)
                result = CTypeSizeof(subobj)
            else:
                raise NotImplementedError("Not implemented!")

        elif isinstance(ast, c_ast.Constant):
            result = int(ast.value, 0)
        elif isinstance(ast, c_ast.Cast):
            # TODO: Can trunc integers?
            result = self.ast_eval_int(ast.expr)
        else:
            raise NotImplementedError("Not implemented!")
        return result 
開發者ID:cea-sec,項目名稱:miasm,代碼行數:48,代碼來源:ctypesmngr.py

示例14: visit_Switch

# 需要導入模塊: from pycparser import c_ast [as 別名]
# 或者: from pycparser.c_ast import BinaryOp [as 別名]
def visit_Switch(self, node):
        '''
        Switch statement
        Attrs: cond, stmt
        '''

        # Parse condition
        condexpr = self.visit_expr(node.cond)

        # Check that stmt is a compound of "case"/"defaults"
        # and covert to "if-then-else"
        # TODO: Check only one "case"/"default"
        if isinstance(node.stmt, c_ast.Compound):

            n = len(node.stmt.block_items)

            def convert(i):

                if i >= n:
                    return

                item = node.stmt.block_items[i]

                # Item statement
                stmt = (c_ast.Compound(item.stmts, coord=item.coord)
                        if isinstance(item.stmts, list) else item.stmts)

                if i == (n - 1) and isinstance(item, c_ast.Default):
                    return stmt
                    
                if isinstance(item, c_ast.Case):
                    next = convert(i + 1)

                    ifcond = c_ast.BinaryOp('==', node.cond, item.expr,
                                            coord=item.expr.coord)
                    return c_ast.If(ifcond, stmt, next, coord=item.expr.coord)

            stmt = convert(0)
            if stmt:
                insw = self.inswitch
                self.inswitch = True
                
                res = self.visit(stmt)
                
                self.inswitch = insw
                
                return res

        # Otherwise not-supported
        raise NotSupported("Switch statement", line=node.coord.line) 
開發者ID:iradicek,項目名稱:clara,代碼行數:52,代碼來源:c_parser.py


注:本文中的pycparser.c_ast.BinaryOp方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。