0

Does pycparser supports user defined types? I want to get list of functions with user defined type as return type from *.C file.

pipsik
  • 219
  • 1
  • 2
  • 9

1 Answers1

2

Sure it does. You just want to write a visitor for FuncDef nodes.

The FuncDef contains a Decl, whose type child is a FuncDecl. This FuncDecl has the return type as its type child.

The return type is either a TypeDecl, in which case the type identifier is its type child, or it's a PtrDecl, in which case its type child is the TypeDecl, whose type child is the type identifier.

Got that? Heres an example FuncDef visitor that prints the name and return type of every function:

class FuncDefVisitor(c_ast.NodeVisitor):
"""
A simple visitor for FuncDef nodes that prints the names and
return types of definitions.
"""
def visit_FuncDef(self, node):
    return_type = node.decl.type.type
    if type(return_type) == c_ast.TypeDecl:
        identifier = return_type.type
    else: # type(return_type) == c_ast.PtrDecl
        identifier = return_type.type.type
    print("{}: {}".format(node.decl.name, identifier.names))

Here's the output when parsing the hash.c example file in the cparser distribution:

hash_func: ['unsigned', 'int']
HashCreate: ['ReturnCode']
HashInsert: ['ReturnCode']
HashFind: ['Entry']
HashRemove: ['ReturnCode']
HashPrint: ['void']
HashDestroy: ['void']

Now you just need to filter out the built-in types, or filter for the UDTs you're interested in.

Louisiana Hasek
  • 425
  • 2
  • 7