How to use the pycparser.c_ast.UnaryOp function in pycparser

To help you get started, we’ve selected a few pycparser 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 eliben / pycparser / pycparser / c_generator.py View on Github external
def _generate_stmt(self, n, add_indent=False):
        """ Generation from a statement node. This method exists as a wrapper
            for individual visit_* methods to handle different treatment of
            some statements in this context.
        """
        typ = type(n)
        if add_indent: self.indent_level += 2
        indent = self._make_indent()
        if add_indent: self.indent_level -= 2

        if typ in (
                c_ast.Decl, c_ast.Assignment, c_ast.Cast, c_ast.UnaryOp,
                c_ast.BinaryOp, c_ast.TernaryOp, c_ast.FuncCall, c_ast.ArrayRef,
                c_ast.StructRef, c_ast.Constant, c_ast.ID, c_ast.Typedef,
                c_ast.ExprList):
            # These can also appear in an expression context so no semicolon
            # is added to them automatically
            #
            return indent + self.visit(n) + ';\n'
        elif typ in (c_ast.Compound,):
            # No extra indentation required before the opening brace of a
            # compound - because it consists of multiple lines it has to
            # compute its own indentation.
            #
            return self.visit(n)
        else:
            return indent + self.visit(n) + '\n'
github jamie-pate / jstruct / parse / annotations.py View on Github external
def sizeof(self, type_decl):
        anonymous_type_decl = self.anonymize_type_decl(type_decl)
        return c_ast.UnaryOp('sizeof', c_ast.Typename(None, [], anonymous_type_decl))
github simonlindholm / decomp-permuter / src / randomizer.py View on Github external
def visitor(expr: Expression) -> None:
                if DEBUG_EAGER_TYPES:
                    decayed_expr_type(expr, typemap)

                if not region.contains_node(expr):
                    return

                orig_expr = expr
                if should_make_ptr:
                    if not ast_util.is_lvalue(expr):
                        return
                    expr = ca.UnaryOp("&", expr)

                eind = einds.get(expr, 0)
                prev_write, _ = surrounding_writes(expr, orig_expr)

                for place in assignment_cands[::-1]:
                    # If expr contains an ID which is written to within
                    # [place, expr), bail out; we're trying to move the
                    # assignment too high up.
                    # TODO: also fail on moving past function calls, or
                    # possibly-aliasing writes.
                    if indices[place[2]] <= prev_write:
                        break

                    # Make far-away places less likely, and similarly for
                    # trivial expressions.
                    eind += 1
github networkupstools / nut / scripts / DMF / jsonify-mib.py View on Github external
def _visit_info_lkp_t (self, node):
        # Depending on version of NUT and presence of WITH_SNMP_LKP_FUN macro,
        # the source code structure can have 2 fields (oid, value) or 4 fields
        # adding (fun, nuf) pointers to lookup processing functions.
        ret = []
        for _, ilist in node.init.children ():
            key_node = ilist.exprs [0]
            if isinstance (key_node, c_ast.UnaryOp):
                key = -1 * int (key_node.expr.value)
            else:
                key = int (key_node.value)

            # array ends with {0, NULL} or {0, NULL, NULL, NULL}
            if isinstance (ilist.exprs [1], c_ast.Cast):
                continue

            # in some pycparser versions this check for {0, NULL} works instead
            if ( key == 0 ):
                if ( ilist.exprs [1].value.strip ('"') == "0" ):
                    # No quoted string for value
                    continue
                elif ( ilist.exprs [1] == "0" ):
                    # Numeric null pointer for value
                    continue
github cloudera / hue / desktop / core / ext-py / cffi-1.5.2 / cffi / cparser.py View on Github external
if s.startswith('0x') or s.startswith('0X'):
                    return int(s, 16)
                return int(s, 8)
            elif '1' <= s[0] <= '9':
                return int(s, 10)
            elif s[0] == "'" and s[-1] == "'" and (
                    len(s) == 3 or (len(s) == 4 and s[1] == "\\")):
                return ord(s[-2])
            else:
                raise api.CDefError("invalid constant %r" % (s,))
        #
        if (isinstance(exprnode, pycparser.c_ast.UnaryOp) and
                exprnode.op == '+'):
            return self._parse_constant(exprnode.expr)
        #
        if (isinstance(exprnode, pycparser.c_ast.UnaryOp) and
                exprnode.op == '-'):
            return -self._parse_constant(exprnode.expr)
        # load previously defined int constant
        if (isinstance(exprnode, pycparser.c_ast.ID) and
                exprnode.name in self._int_constants):
            return self._int_constants[exprnode.name]
        #
        if partial_length_ok:
            if (isinstance(exprnode, pycparser.c_ast.ID) and
                    exprnode.name == '__dotdotdotarray__'):
                self._partial_length = True
                return '...'
        #
        raise api.FFIError(":%d: unsupported expression: expected a "
                           "simple numeric constant" % exprnode.coord.line)
github simonlindholm / decomp-permuter / src / randomizer.py View on Github external
def to_array(node: ca.BinaryOp) -> ca.ArrayRef:
        """Change a BinaryOp, a + b, to an ArrayRef, a[b]
        The operator is expected to be + or -"""
        # TODO: Permute binops like to_binop() does
        if node.op == "-":
            # Convert to a[-b]
            node.right = ca.UnaryOp("-", node.right)
        return ca.ArrayRef(node.left, node.right)
github dgelessus / pythonista-c-utils / cffipp / cffi_patches.py View on Github external
def _parse_constant(self, exprnode, **kwargs):
		if isinstance(exprnode, pycparser.c_ast.UnaryOp):
			if exprnode.op == "+":
				return self._parse_constant(exprnode.expr)
			elif exprnode.op == "-":
				return -self._parse_constant(exprnode.expr)
			elif exprnode.op == "~":
				return ~self._parse_constant(exprnode.expr)
			elif exprnode.op == "!":
				return int(not self._parse_constant(exprnode.expr))
			elif exprnode.op == "sizeof":
				tp, quals = self._get_type_and_quals(exprnode.expr)
				return self._ffi.sizeof(tp.build_backend_type(self._ffi, []))
		elif isinstance(exprnode, pycparser.c_ast.BinaryOp):
			if exprnode.op == "+":
				return self._parse_constant(exprnode.left) + self._parse_constant(exprnode.right)
			elif exprnode.op == "-":
				return self._parse_constant(exprnode.left) - self._parse_constant(exprnode.right)
github cea-sec / miasm / miasm / core / objc.py View on Github external
s_name = name
            s_field = ExprId(field, 64)
            obj = ExprOp("field", s_name, s_field)
        else:
            raise RuntimeError("Unknown struct access")
    elif isinstance(ast, c_ast.UnaryOp) and ast.op == "&":
        tmp = ast_get_c_access_expr(ast.expr, expr_types, lvl + 1)
        obj = ExprOp("addr", tmp)
    elif isinstance(ast, c_ast.ArrayRef):
        tmp = ast_get_c_access_expr(ast.name, expr_types, lvl + 1)
        index = ast_get_c_access_expr(ast.subscript, expr_types, lvl + 1)
        obj = ExprOp("[]", tmp, index)
    elif isinstance(ast, c_ast.ID):
        assert ast.name in expr_types
        obj = ExprId(ast.name, 64)
    elif isinstance(ast, c_ast.UnaryOp) and ast.op == "*":
        tmp = ast_get_c_access_expr(ast.expr, expr_types, lvl + 1)
        obj = ExprOp("deref", tmp)
    else:
        raise NotImplementedError("Unknown type")
    return obj
github cea-sec / miasm / miasm / core / objc.py View on Github external
if isinstance(ast, c_ast.Constant):
        obj = ExprInt(int(ast.value), 64)
    elif isinstance(ast, c_ast.StructRef):
        name, field = ast.name, ast.field.name
        name = ast_get_c_access_expr(name, expr_types)
        if ast.type == "->":
            s_name = name
            s_field = ExprId(field, 64)
            obj = ExprOp('->', s_name, s_field)
        elif ast.type == ".":
            s_name = name
            s_field = ExprId(field, 64)
            obj = ExprOp("field", s_name, s_field)
        else:
            raise RuntimeError("Unknown struct access")
    elif isinstance(ast, c_ast.UnaryOp) and ast.op == "&":
        tmp = ast_get_c_access_expr(ast.expr, expr_types, lvl + 1)
        obj = ExprOp("addr", tmp)
    elif isinstance(ast, c_ast.ArrayRef):
        tmp = ast_get_c_access_expr(ast.name, expr_types, lvl + 1)
        index = ast_get_c_access_expr(ast.subscript, expr_types, lvl + 1)
        obj = ExprOp("[]", tmp, index)
    elif isinstance(ast, c_ast.ID):
        assert ast.name in expr_types
        obj = ExprId(ast.name, 64)
    elif isinstance(ast, c_ast.UnaryOp) and ast.op == "*":
        tmp = ast_get_c_access_expr(ast.expr, expr_types, lvl + 1)
        obj = ExprOp("deref", tmp)
    else:
        raise NotImplementedError("Unknown type")
    return obj
github LedgerHQ / nanos-secure-sdk / pycparser / c_parser.py View on Github external
def p_postfix_expression_5(self, p):
        """ postfix_expression  : postfix_expression PLUSPLUS
                                | postfix_expression MINUSMINUS
        """
        p[0] = c_ast.UnaryOp('p' + p[2], p[1], p[1].coord)