- http://llvm.org/svn/llvm-project/cfe/trunk/bindings/python/examples/cindex/cindex-dump.py
- http://d.hatena.ne.jp/osyo-manga/20140118/1390045795
Pythonをインストール
- https://www.python.org/downloads/
- 2.7.10を使用
LLVMをダウンロード&インストール
clangでASTを表示するならこれでOK。
> clang.exe -Xclang -ast-dump -fsyntax-only test.cpp
PIPでclangをインストール
pip install asciitree pip install clang
tset.cpp
#include <string>
#include <iostream>
class Test {
public:
Test() {};
virtual void method1() {
std::cout << "Test::method1()" << std::endl;
};
};
int main(int argc, char *argv[])
{
int a, b, c;
a = 1;
b = 2;
c = a + b;
Test *test = new Test();
test->method1();
delete test;
test = NULL;
}
dump-ast.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import clang.cindex
import pprint
def traverse(n, i=0):
print ' ' * i,
print n.kind,
print " : ",
print n.spelling,
print
for c in n.get_children():
traverse(c, i=i+1)
def main():
clang.cindex.Config.set_library_file('C:/Program Files (x86)/LLVM/bin/libclang.dll')
index = clang.cindex.Index.create()
translation_unit = index.parse("test.cpp", ['-x', 'c++'])
traverse(translation_unit.cursor)
if __name__ == '__main__':
main()
実行結果
> python.exe dump-ast.py test.cpp
CursorKind.TRANSLATION_UNIT : test.cpp
CursorKind.CLASS_DECL : Test
CursorKind.CXX_ACCESS_SPEC_DECL :
CursorKind.CONSTRUCTOR : Test
CursorKind.COMPOUND_STMT :
CursorKind.CXX_METHOD : method1
CursorKind.COMPOUND_STMT :
CursorKind.FUNCTION_DECL : main
CursorKind.PARM_DECL : argc
CursorKind.PARM_DECL : argv
CursorKind.COMPOUND_STMT :
CursorKind.DECL_STMT :
CursorKind.VAR_DECL : a
CursorKind.VAR_DECL : b
CursorKind.VAR_DECL : c
CursorKind.BINARY_OPERATOR :
CursorKind.DECL_REF_EXPR : a
CursorKind.INTEGER_LITERAL :
CursorKind.BINARY_OPERATOR :
CursorKind.DECL_REF_EXPR : b
CursorKind.INTEGER_LITERAL :
CursorKind.BINARY_OPERATOR :
CursorKind.DECL_REF_EXPR : c
CursorKind.BINARY_OPERATOR :
CursorKind.UNEXPOSED_EXPR : a
CursorKind.DECL_REF_EXPR : a
CursorKind.UNEXPOSED_EXPR : b
CursorKind.DECL_REF_EXPR : b
CursorKind.DECL_STMT :
CursorKind.VAR_DECL : test
CursorKind.TYPE_REF : class Test
CursorKind.CXX_NEW_EXPR :
CursorKind.TYPE_REF : class Test
CursorKind.CALL_EXPR : Test
CursorKind.CALL_EXPR : method1
CursorKind.MEMBER_REF_EXPR : method1
CursorKind.UNEXPOSED_EXPR : test
CursorKind.DECL_REF_EXPR : test
CursorKind.CXX_DELETE_EXPR :
CursorKind.UNEXPOSED_EXPR : test
CursorKind.DECL_REF_EXPR : test