Python pycparser.c_ast.IdentifierType() Examples

The following are 17 code examples of pycparser.c_ast.IdentifierType(). 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 pycparser.c_ast , or try the search function .
Example #1
Source File: cdecl.py    From SwiftKitten with MIT License 5 votes vote down vote up
def _explain_type(decl):
    """ Recursively explains a type decl node
    """
    typ = type(decl)

    if typ == c_ast.TypeDecl:
        quals = ' '.join(decl.quals) + ' ' if decl.quals else ''
        return quals + _explain_type(decl.type)
    elif typ == c_ast.Typename or typ == c_ast.Decl:
        return _explain_type(decl.type)
    elif typ == c_ast.IdentifierType:
        return ' '.join(decl.names)
    elif typ == c_ast.PtrDecl:
        quals = ' '.join(decl.quals) + ' ' if decl.quals else ''
        return quals + 'pointer to ' + _explain_type(decl.type)
    elif typ == c_ast.ArrayDecl:
        arr = 'array'
        if decl.dim: arr += '[%s]' % decl.dim.value

        return arr + " of " + _explain_type(decl.type)

    elif typ == c_ast.FuncDecl:
        if decl.args:
            params = [_explain_type(param) for param in decl.args.params]
            args = ', '.join(params)
        else:
            args = ''

        return ('function(%s) returning ' % (args) +
                _explain_type(decl.type)) 
Example #2
Source File: map_hal2intercepts.py    From halucinator with GNU General Public License v3.0 5 votes vote down vote up
def is_type_void(node):
    '''
        Checks if the nodes type is void
        Return True if void
    '''
    ty = node.type
    if type(ty) == c_ast.IdentifierType and 'void' in ty.names:
        return True
    else:
        return False 
Example #3
Source File: kernel.py    From kerncraft with GNU Affero General Public License v3.0 5 votes vote down vote up
def _build_kernel_function_declaration(self, name='kernel'):
        """Build and return kernel function declaration"""
        array_declarations, array_dimensions = self._build_array_declarations(with_init=False)
        const_declarations = self._build_const_declartions(with_init=False)
        return c_ast.FuncDecl(args=c_ast.ParamList(params=array_declarations +
                                                          const_declarations),
                              type=c_ast.TypeDecl(declname=name,
                                                  quals=[],
                                                  type=c_ast.IdentifierType(names=['void']))) 
Example #4
Source File: kernel.py    From kerncraft with GNU Affero General Public License v3.0 5 votes vote down vote up
def _build_const_declartions(self, with_init=True):
        """
        Generate constants declarations

        :return: list of declarations
        """
        decls = []

        # Use type as provided by user in loop indices
        index_type = self.get_index_type()

        i = 2  # subscript for cli input, 1 is reserved for repeat
        for k in self.constants:
            # const long long N = strtoul(argv[2])
            # with increasing N and 1
            # TODO change subscript of argv depending on constant count
            type_decl = c_ast.TypeDecl(k.name, ['const'], c_ast.IdentifierType(index_type))
            init = None
            if with_init:
                init = c_ast.FuncCall(
                    c_ast.ID('atoi'),
                    c_ast.ExprList([c_ast.ArrayRef(c_ast.ID('argv'),
                                                   c_ast.Constant('int', str(i)))]))
            i += 1
            decls.append(c_ast.Decl(
                k.name, ['const'], [], [],
                type_decl, init, None))

        return decls 
Example #5
Source File: c_types.py    From mips_to_c with GNU General Public License v3.0 5 votes vote down vote up
def get_primitive_list(type: CType, typemap: TypeMap) -> Optional[List[str]]:
    type = resolve_typedefs(type, typemap)
    if not isinstance(type, TypeDecl):
        return None
    inner_type = type.type
    if isinstance(inner_type, ca.Enum):
        return ["int"]
    if isinstance(inner_type, ca.IdentifierType):
        return inner_type.names
    return None 
Example #6
Source File: c_types.py    From mips_to_c with GNU General Public License v3.0 5 votes vote down vote up
def primitive_size(type: Union[ca.Enum, ca.IdentifierType]) -> int:
    if isinstance(type, ca.Enum):
        return 4
    names = type.names
    if "double" in names:
        return 8
    if "float" in names:
        return 4
    if "short" in names:
        return 2
    if "char" in names:
        return 1
    if names.count("long") == 2:
        return 8
    return 4 
Example #7
Source File: c_types.py    From mips_to_c with GNU General Public License v3.0 5 votes vote down vote up
def is_void(type: CType) -> bool:
    return (
        isinstance(type, ca.TypeDecl)
        and isinstance(type.type, ca.IdentifierType)
        and type.type.names == ["void"]
    ) 
Example #8
Source File: c_types.py    From mips_to_c with GNU General Public License v3.0 5 votes vote down vote up
def resolve_typedefs(type: CType, typemap: TypeMap) -> CType:
    while (
        isinstance(type, TypeDecl)
        and isinstance(type.type, IdentifierType)
        and len(type.type.names) == 1
        and type.type.names[0] in typemap.typedefs
    ):
        type = typemap.typedefs[type.type.names[0]]
    return type 
Example #9
Source File: c_types.py    From mips_to_c with GNU General Public License v3.0 5 votes vote down vote up
def basic_type(names: List[str]) -> TypeDecl:
    idtype = IdentifierType(names=names)
    return TypeDecl(declname=None, quals=[], type=idtype) 
Example #10
Source File: ctypesmngr.py    From miasm with GNU General Public License v2.0 5 votes vote down vote up
def ast_parse_identifiertype(self, ast):
        """Parse ast IdentifierType"""
        return CTypeId(*ast.names) 
Example #11
Source File: ctypesmngr.py    From miasm with GNU General Public License v2.0 5 votes vote down vote up
def ast_to_typeid_identifiertype(self, ast):
        """Return the CTypeBase of an IdentifierType ast"""
        return CTypeId(*ast.names) 
Example #12
Source File: ctypesmngr.py    From miasm with GNU General Public License v2.0 5 votes vote down vote up
def visit_TypeDecl(self, node):
        """Retrieve the name in a function declaration:
        Only one IdentifierType is present"""
        self.node_name = node 
Example #13
Source File: ctypesmngr.py    From miasm with GNU General Public License v2.0 4 votes vote down vote up
def __init__(self, knowntypes=None, knowntypedefs=None):
        if knowntypes is None:
            knowntypes = {}
        if knowntypedefs is None:
            knowntypedefs = {}

        self._types = dict(knowntypes)
        self._typedefs = dict(knowntypedefs)
        self.cpt = 0
        self.loc_to_decl_info = {}
        self.parser = c_parser.CParser()
        self._cpt_decl = 0


        self.ast_to_typeid_rules = {
            c_ast.Struct: self.ast_to_typeid_struct,
            c_ast.Union: self.ast_to_typeid_union,
            c_ast.IdentifierType: self.ast_to_typeid_identifiertype,
            c_ast.TypeDecl: self.ast_to_typeid_typedecl,
            c_ast.Decl: self.ast_to_typeid_decl,
            c_ast.Typename: self.ast_to_typeid_typename,
            c_ast.FuncDecl: self.ast_to_typeid_funcdecl,
            c_ast.Enum: self.ast_to_typeid_enum,
            c_ast.PtrDecl: self.ast_to_typeid_ptrdecl,
            c_ast.EllipsisParam: self.ast_to_typeid_ellipsisparam,
            c_ast.ArrayDecl: self.ast_to_typeid_arraydecl,
        }

        self.ast_parse_rules = {
            c_ast.Struct: self.ast_parse_struct,
            c_ast.Union: self.ast_parse_union,
            c_ast.Typedef: self.ast_parse_typedef,
            c_ast.TypeDecl: self.ast_parse_typedecl,
            c_ast.IdentifierType: self.ast_parse_identifiertype,
            c_ast.Decl: self.ast_parse_decl,
            c_ast.PtrDecl: self.ast_parse_ptrdecl,
            c_ast.Enum: self.ast_parse_enum,
            c_ast.ArrayDecl: self.ast_parse_arraydecl,
            c_ast.FuncDecl: self.ast_parse_funcdecl,
            c_ast.FuncDef: self.ast_parse_funcdef,
            c_ast.Pragma: self.ast_parse_pragma,
        } 
Example #14
Source File: extract_ptrace_constants.py    From ptracer with Apache License 2.0 4 votes vote down vote up
def render_type(typedecl):
    res = []

    if isinstance(typedecl, (c_ast.TypeDecl, c_ast.Typename)):
        res.extend(typedecl.quals)
        res.extend(render_type(typedecl.type))

    elif isinstance(typedecl, c_ast.PtrDecl):
        res.extend(typedecl.quals)
        res.extend(render_type(typedecl.type))
        res.append('*')

    elif isinstance(typedecl, c_ast.IdentifierType):
        res.extend(typedecl.names)

    elif isinstance(typedecl, c_ast.Struct):
        res.extend(['struct', typedecl.name])

    elif isinstance(typedecl, c_ast.Union):
        res.extend(['union', typedecl.name])

    elif isinstance(typedecl, (c_ast.FuncDecl, ext_c_parser.FuncDeclExt)):
        ret = render_type(typedecl.type)
        args = []
        for param in typedecl.args.params:
            args.append(' '.join(render_type(param)))
        ret.append('({})'.format(', '.join(args)))

        res.extend(ret)

    elif isinstance(typedecl, c_ast.ArrayDecl):
        res.extend(render_type(typedecl.type))
        if typedecl.dim is None:
            res.append('[]')
        elif isinstance(typedecl.dim, c_ast.Constant):
            res.append('[{}]'.format(typedecl.dim.value))
        else:
            die('non-constant dimension in array declaration')

    else:
        die('unexpected {!r}'.format(typedecl))

    return res 
Example #15
Source File: extract_ptrace_constants.py    From ptracer with Apache License 2.0 4 votes vote down vote up
def get_ctypes_type(typedecl, typedefs):
    ptr_indirection = 0

    if isinstance(typedecl, c_ast.TypeDecl):
        if isinstance(typedecl.type, c_ast.IdentifierType):
            tnames = typedecl.type.names

            while True:
                if ((len(tnames) == 1 and tnames[0] in typedefs) or
                        (tnames[-1] in typedefs and tnames[-2] not in
                            {'struct', 'union'})):
                    tnames = list(tnames[:-1]) + list(typedefs[tnames[-1]])
                else:
                    break

            ptr_indirection = 1 if tnames[-1] == '*' else 0
            if ptr_indirection:
                tnames = tnames[:-1]

            if len(tnames) > 1 and tnames[-2] == 'struct':
                ctype = 'ctypes.c_void_p'
                ptr_indirection = 0
            elif len(tnames) > 1 and tnames[-2] == 'union':
                ctype = 'ctypes.c_void_p'
                ptr_indirection = 0
            else:
                ctype = ctype_map.get(tuple(tnames))
                if ctype is None:
                    die('unrecognized C type: {}'.format(' '.join(tnames)))

        elif isinstance(typedecl.type, c_ast.Struct):
            ctype = 'ctypes.c_void_p'

        elif isinstance(typedecl.type, c_ast.Union):
            ctype = 'ctypes.c_void_p'

        else:
            die('unexpected syntax in type declaration: {!r}'.format(
                typedecl.type))

    elif isinstance(typedecl, c_ast.PtrDecl):
        ctype, ptr_indirection = get_ctypes_type(
            typedecl.type, typedefs)

        if ctype != 'ctypes.c_void_p':
            ptr_indirection += 1

    elif isinstance(typedecl, c_ast.ArrayDecl):
        array_type, ptr_indirection = get_ctypes_type(typedecl.type, typedefs)
        dim = fold_const_expr(typedecl.dim, typedefs)
        ctype = '{} * {}'.format(array_type, dim)

    else:
        die('unexpected syntax in type declaration: {!r}'.format(
            typedecl))

    return ctype, ptr_indirection 
Example #16
Source File: cparse.py    From nightmare with GNU General Public License v2.0 4 votes vote down vote up
def __init__(self, psize=4, bigend=False):

        self.psize = psize
        self.pclass = vs_prim.v_ptr32

        self.cls_parsers = {
            c_ast.Decl:             self.c_getVsDecl,
            c_ast.Struct:           self.c_getVsStruct,
            c_ast.FileAST:          self.c_getFileAst,
            c_ast.PtrDecl:          self.c_getPointer,
            #c_ast.FuncDecl:         self.c_getFuncDecl,
            c_ast.Constant:         self.c_getConstant,
            c_ast.TypeDecl:         self.c_getVsType,
            c_ast.ArrayDecl:        self.c_getVsArray,
            c_ast.IdentifierType:   self.c_getIdentType,
        }

        self.vs_ctypes = {
            ('char',):                  vs_prim.v_int8,
            ('unsigned','char'):        vs_prim.v_uint8,

            ('short',):                 vs_prim.v_int16,
            ('short','int'):            vs_prim.v_int16,

            ('unsigned', 'short',):     vs_prim.v_uint16,
            ('unsigned', 'short','int'):vs_prim.v_uint16,

            ('int',):                   vs_prim.v_int32,
            ('unsigned','int',):        vs_prim.v_uint32,

            ('long',):                  vs_prim.v_int32,
            ('long','int'):             vs_prim.v_int32,

            ('unsigned','long',):       vs_prim.v_uint32,
            ('unsigned','long','int'):  vs_prim.v_uint32,
        }

        if psize == 8:
            self.pclass = vs_prim.v_ptr64
            self.vs_ctypes.update({
                ('long',):                  vs_prim.v_int64,
                ('long','int'):             vs_prim.v_int64,

                ('unsigned','long',):       vs_prim.v_uint64,
                ('unsigned','long','int'):  vs_prim.v_uint64,
            }) 
Example #17
Source File: cparse.py    From CanCat with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def __init__(self, psize=4, bigend=False):

        self.psize = psize
        self.pclass = vs_prim.v_ptr32

        self.cls_parsers = {
            c_ast.Decl:             self.c_getVsDecl,
            c_ast.Struct:           self.c_getVsStruct,
            c_ast.FileAST:          self.c_getFileAst,
            c_ast.PtrDecl:          self.c_getPointer,
            #c_ast.FuncDecl:         self.c_getFuncDecl,
            c_ast.Constant:         self.c_getConstant,
            c_ast.TypeDecl:         self.c_getVsType,
            c_ast.ArrayDecl:        self.c_getVsArray,
            c_ast.IdentifierType:   self.c_getIdentType,
        }

        self.vs_ctypes = {
            ('char',):                  vs_prim.v_int8,
            ('unsigned','char'):        vs_prim.v_uint8,

            ('short',):                 vs_prim.v_int16,
            ('short','int'):            vs_prim.v_int16,

            ('unsigned', 'short',):     vs_prim.v_uint16,
            ('unsigned', 'short','int'):vs_prim.v_uint16,

            ('int',):                   vs_prim.v_int32,
            ('unsigned','int',):        vs_prim.v_uint32,

            ('long',):                  vs_prim.v_int32,
            ('long','int'):             vs_prim.v_int32,

            ('unsigned','long',):       vs_prim.v_uint32,
            ('unsigned','long','int'):  vs_prim.v_uint32,
        }

        if psize == 8:
            self.pclass = vs_prim.v_ptr64
            self.vs_ctypes.update({
                ('long',):                  vs_prim.v_int64,
                ('long','int'):             vs_prim.v_int64,

                ('unsigned','long',):       vs_prim.v_uint64,
                ('unsigned','long','int'):  vs_prim.v_uint64,
            })