blob: 552f86060678b77d254bef8be8a3ea75207a85d6 [file] [log] [blame]
Eli Benderskya2915862012-06-23 06:25:53 +03001#-----------------------------------------------------------------
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
Eli Bendersky904cecd2015-12-12 14:47:21 -08008# pycparser. Call it from the root directory of pycparser.
Eli Benderskya2915862012-06-23 06:25:53 +03009#
Eli Bendersky331f81f2015-04-21 14:42:56 -070010# Copyright (C) 2008-2015, Eli Bendersky
Eli Benderskya2915862012-06-23 06:25:53 +030011# License: BSD
12#-----------------------------------------------------------------
13from __future__ import print_function
14import sys
15
16# This is not required if you've installed pycparser into
17# your site-packages/ with setup.py
Eli Benderskya2915862012-06-23 06:25:53 +030018sys.path.extend(['.', '..'])
19
20from pycparser import c_parser, c_ast, parse_file
21
22
23# A simple visitor for FuncDef nodes that prints the names and
24# locations of function definitions.
Eli Benderskya2915862012-06-23 06:25:53 +030025class FuncDefVisitor(c_ast.NodeVisitor):
26 def visit_FuncDef(self, node):
27 print('%s at %s' % (node.decl.name, node.decl.coord))
28
29
30def show_func_defs(filename):
31 # Note that cpp is used. Provide a path to your own cpp or
32 # make sure one exists in PATH.
Eli Bendersky904cecd2015-12-12 14:47:21 -080033 ast = parse_file(filename, use_cpp=True,
34 cpp_args=r'-Iutils/fake_libc_include')
Eli Benderskya2915862012-06-23 06:25:53 +030035
36 v = FuncDefVisitor()
37 v.visit(ast)
38
39
40if __name__ == "__main__":
41 if len(sys.argv) > 1:
42 filename = sys.argv[1]
43 else:
Eli Bendersky331f81f2015-04-21 14:42:56 -070044 filename = 'examples/c_files/memmgr.c'
Eli Benderskya2915862012-06-23 06:25:53 +030045
46 show_func_defs(filename)