Created
December 30, 2016 08:41
-
-
Save taktoa/9be18da9c27f31818c4e7bbcefe15c09 to your computer and use it in GitHub Desktop.
Minimal Clang code using Python binding to traverse a C++ AST
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" Usage: call with <filename> | |
""" | |
# | |
# Understanding CLang AST : http://clang.llvm.org/docs/IntroductionToTheClangAST.html | |
# | |
# Requirements | |
# | |
# 1. Install Clang : Visit http://llvm.org/releases/download.html | |
# | |
# 2. pip install clang | |
# | |
# Note : Make sure that your Python runtime and Clang are same architecture | |
# | |
import sys | |
import clang.cindex | |
def trimClangNodeName(nodeName): | |
ret = str(nodeName) | |
ret = ret.split(".")[1] | |
return ret | |
def printASTNode(node, level): | |
for i in range(0, level): | |
print '-', | |
print trimClangNodeName(node.kind) | |
def traverseAST(node, level): | |
if node is not None: | |
level = level+1 | |
printASTNode(node, level) | |
# Recurse for children of this node | |
for childNode in node.get_children(): | |
traverseAST(childNode, level) | |
level = level-1 | |
#If the line below fails , set Clang library path with clang.cindex.Config.set_library_path | |
index = clang.cindex.Index.create() | |
translationUnit = index.parse(sys.argv[1]) | |
rootNode = translationUnit.cursor | |
traverseAST(rootNode, 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment