Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traversing the Clang AST using Python

I am working on using clang bingings python to travers c/c++ code into AST,how can I get a tree based AST structure? Some pointers on where to start, tutorials or anything in this regard will be of great help!!!

I found a very useful work(If you want to check this out ,here is the link:https://www.chess.com/blog/lockijazz/using-python-to-traverse-and-modify-clang-s-ast-tree) and tried his code,unfortunately I didn't get a useful output.

function_calls = []           
function_declarations = []     
def traverse(node):

    for child in node.get_children():
        traverse(child)

    if node.type == clang.cindex.CursorKind.CALL_EXPR:
        function_calls.append(node)

    if node.type == clang.cindex.CursorKind.FUNCTION_DECL:
        function_declarations.append(node)


    print 'Found %s [line=%s, col=%s]' % (node.displayname, node.location.line, node.location.column)

clang.cindex.Config.set_library_path("/Users/tomgong/Desktop/build/lib")
index = clang.cindex.Index.create()

tu = index.parse(sys.argv[1])

root = tu.cursor        
traverse(root)
like image 357
penguin Avatar asked Oct 19 '25 05:10

penguin


2 Answers

Just in case anyone was having trouble still, I found that if you should be using kind instead of type

you can run clang.cindex.CursorKind.get_all_kinds() to retrieve all kinds and see that when using the node.type does not appear in any of them.

function_calls = []           
function_declarations = []     
def traverse(node):

    for child in node.get_children():
        traverse(child)

    if node.kind == clang.cindex.CursorKind.CALL_EXPR:
        function_calls.append(node)

    if node.kind == clang.cindex.CursorKind.FUNCTION_DECL:
        function_declarations.append(node)


    print 'Found %s [line=%s, col=%s]' % (node.displayname, node.location.line, node.location.column)

clang.cindex.Config.set_library_path("/Users/tomgong/Desktop/build/lib")
index = clang.cindex.Index.create()

tu = index.parse(sys.argv[1])

root = tu.cursor        
traverse(root)
like image 83
AY157 Avatar answered Oct 22 '25 05:10

AY157


I have been using pycparser in order to do obtain the AST of C/C++ source code and explore the same using python.

You can find the API for exploring the AST in this example from the repository.

like image 35
Abhirup Das Avatar answered Oct 22 '25 03:10

Abhirup Das