| 1 | #----------------------------------------------------------------- |
| 2 | # pycparser: func_defs.py |
| 3 | # |
| 4 | # Using pycparser for printing out all the functions defined in a |
| 5 | # C file. |
| 6 | # |
| 7 | # This is a simple example of traversing the AST generated by |
| 8 | # pycparser. Call it from the root directory of pycparser. |
| 9 | # |
| 10 | # Eli Bendersky [https://eli.thegreenplace.net/] |
| 11 | # License: BSD |
| 12 | #----------------------------------------------------------------- |
| 13 | import sys |
| 14 | |
| 15 | # This is not required if you've installed pycparser into |
| 16 | # your site-packages/ with setup.py |
| 17 | sys.path.extend(['.', '..']) |
| 18 | |
| 19 | from pycparser import c_ast, parse_file |
| 20 | |
| 21 | |
| 22 | # A simple visitor for FuncDef nodes that prints the names and |
| 23 | # locations of function definitions. |
| 24 | class FuncDefVisitor(c_ast.NodeVisitor): |
| 25 | def visit_FuncDef(self, node): |
| 26 | print('%s at %s' % (node.decl.name, node.decl.coord)) |
| 27 | |
| 28 | |
| 29 | def show_func_defs(filename): |
| 30 | # Note that cpp is used. Provide a path to your own cpp or |
| 31 | # make sure one exists in PATH. |
| 32 | ast = parse_file(filename, use_cpp=True, |
| 33 | cpp_args=r'-Iutils/fake_libc_include') |
| 34 | |
| 35 | v = FuncDefVisitor() |
| 36 | v.visit(ast) |
| 37 | |
| 38 | |
| 39 | if __name__ == "__main__": |
| 40 | if len(sys.argv) > 1: |
| 41 | filename = sys.argv[1] |
| 42 | else: |
| 43 | filename = 'examples/c_files/memmgr.c' |
| 44 | |
| 45 | show_func_defs(filename) |