sla*_*r98 5 c++ python parsing clang abstract-syntax-tree
给定以下 C++ 文件:
class Foo
{
public:
Foo();
void bar(int input);
void another(int input, double & output);
};
void
Foo::bar(int input)
{
input += 1;
}
void
Foo::another(int input, double & output)
{
input += 1;
output = input * 1.2345;
}
Run Code Online (Sandbox Code Playgroud)
如何利用 clang python 绑定来提取这两个方法的定义。我可以使用下面的 python 脚本获取类声明,但我似乎不知道如何提取完整的方法。例如,我想要以下信息:
void
Foo::another(int input, double & output)
{
input += 1;
output = input * 1.2345;
}
Run Code Online (Sandbox Code Playgroud)
Python脚本:
#!/usr/bin/env python
import clang.cindex
clang.cindex.Config.set_library_path('/opt/moose/llvm-3.7.0/lib')
def getCursors(cursor, output, kind):
"""
Recursively extract all the cursors of the given kind.
"""
for c in cursor.get_children():
if c.kind == kind:
output.append(c)
getCursors(c, output, kind)
if __name__ == '__main__':
# Parse the test file
index = clang.cindex.Index.create()
tu = index.parse('method.C', ['-x', 'c++'])
# Extract the parsers
output = []
getCursors(tu.cursor, output, clang.cindex.CursorKind.CXX_METHOD)
# Print the method declarations (How to I get the definitions?)
for c in output:
defn = c.get_definition() # Gives nothing
print defn
print c.extent.start.file, c.extent.start.line, c.extent.end.line # Gives decleration
Run Code Online (Sandbox Code Playgroud)
建议使用以下函数作为解决方案,但它不适用于 clang 3.7。在 3.9 发布之前我无法更新到它,并且我需要支持最新的两个版本的 clang(3.7 和 3.8)。如果添加打印语句,结果表明未找到定义。
def method_definitions(cursor):
for i in cursor.walk_preorder():
print i.kind, i.is_definition() # Added this
if i.kind != CursorKind.CXX_METHOD:
continue
if not i.is_definition():
continue
yield i
Run Code Online (Sandbox Code Playgroud)
运行该方法会产生以下结果,有人知道 clang 3.7 和 3.9 之间发生了什么变化吗?
CursorKind.TRANSLATION_UNIT False
CursorKind.CLASS_DECL True
CursorKind.CXX_ACCESS_SPEC_DECL True
CursorKind.CONSTRUCTOR False
CursorKind.CXX_METHOD False
CursorKind.PARM_DECL True
CursorKind.CXX_METHOD False
CursorKind.PARM_DECL True
CursorKind.PARM_DECL True
Run Code Online (Sandbox Code Playgroud)
你已经非常接近了 - 技巧是使用光标偏移量而不是行/列,并且据我所知,libclang 不会公开源的字节,因此你需要自己读出文本。
以下内容经过测试:
pip install 'clang==3.7')唯一需要注意的是,对于具有宏/标头 YMMV 的更复杂情况。
import clang.cindex
from clang.cindex import *
def method_definitions(cursor):
for i in cursor.walk_preorder():
if i.kind != CursorKind.CXX_METHOD:
continue
if not i.is_definition():
continue
yield i
def extract_definition(cursor):
filename = cursor.location.file.name
with open(filename, 'r') as fh:
contents = fh.read()
return contents[cursor.extent.start.offset: cursor.extent.end.offset]
idx = Index.create()
tu = idx.parse('method.C', ['-x', 'c++'])
defns = method_definitions(tu.cursor)
for defn in defns:
print extract_definition(defn)
Run Code Online (Sandbox Code Playgroud)
这使:
void
Foo::bar(int input)
{
input += 1;
}
void
Foo::another(int input, double & output)
{
input += 1;
output = input * 1.2345;
}
Run Code Online (Sandbox Code Playgroud)