Eli Bendersky | 3921e8e | 2010-05-21 09:05:39 +0300 | [diff] [blame] | 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.
|
| 9 | #
|
eli.bendersky | 1a1e46b | 2011-02-18 15:32:18 +0200 | [diff] [blame] | 10 | # Copyright (C) 2008-2011, Eli Bendersky
|
Eli Bendersky | 3921e8e | 2010-05-21 09:05:39 +0300 | [diff] [blame] | 11 | # License: LGPL
|
| 12 | #-----------------------------------------------------------------
|
eli.bendersky | 1a1e46b | 2011-02-18 15:32:18 +0200 | [diff] [blame] | 13 | from __future__ import print_function
|
Eli Bendersky | 3921e8e | 2010-05-21 09:05:39 +0300 | [diff] [blame] | 14 | import sys
|
| 15 |
|
| 16 | # This is not required if you've installed pycparser into
|
| 17 | # your site-packages/ with setup.py
|
| 18 | #
|
| 19 | sys.path.insert(0, '..')
|
| 20 |
|
| 21 | from pycparser import c_parser, c_ast, parse_file
|
Eli Bendersky | 3921e8e | 2010-05-21 09:05:39 +0300 | [diff] [blame] | 22 |
|
| 23 |
|
| 24 | # A simple visitor for FuncDef nodes that prints the names and
|
| 25 | # locations of function definitions.
|
| 26 | #
|
| 27 | class FuncDefVisitor(c_ast.NodeVisitor):
|
| 28 | def visit_FuncDef(self, node):
|
eli.bendersky | 1a1e46b | 2011-02-18 15:32:18 +0200 | [diff] [blame] | 29 | print('%s at %s' % (node.decl.name, node.decl.coord))
|
Eli Bendersky | 3921e8e | 2010-05-21 09:05:39 +0300 | [diff] [blame] | 30 |
|
| 31 |
|
| 32 | def show_func_defs(filename):
|
| 33 | # Note that cpp is used. Provide a path to your own cpp or
|
| 34 | # make sure one exists in PATH.
|
| 35 | # |
| 36 | ast = parse_file(filename, use_cpp=True)
|
| 37 |
|
| 38 | v = FuncDefVisitor()
|
| 39 | v.visit(ast)
|
| 40 |
|
| 41 |
|
| 42 | if __name__ == "__main__":
|
| 43 | if len(sys.argv) > 1:
|
| 44 | filename = sys.argv[1]
|
| 45 | else:
|
| 46 | filename = 'c_files/memmgr.c'
|
| 47 |
|
| 48 | show_func_defs(filename)
|
| 49 |
|
| 50 |
|
| 51 |
|