使用libclang在python中解析C但生成了错误的AST

时间:2015-12-17 07:43:06

标签: python libclang

我想使用libclang绑定python来生成C代码的AST。好的,源代码如下所示。

#include <stdlib.h>
#include "adlist.h"
#include "zmalloc.h"


list *listCreate(void)
{
    struct list *list;

    if ((list = zmalloc(sizeof(*list))) == NULL)
        return NULL;
    list->head = list->tail = NULL;
    list->len = 0;
    list->dup = NULL;
    list->free = NULL;
    list->match = NULL;
    return list;
}

我写的一个实现:

#!/usr/bin/python
# vim: set fileencoding=utf-8


import clang.cindex
import asciitree
import sys

def node_children(node):
    return (c for c in node.get_children() if c.location.file.name == sys.argv[1])

def print_node(node):
    text = node.spelling or node.displayname
    kind = str(node.kind)[str(node.kind).index('.')+1:]
    return '{} {}'.format(kind, text)

if len(sys.argv) != 2:
    print("Usage: dump_ast.py [header file name]")
    sys.exit()

clang.cindex.Config.set_library_file('/usr/lib/llvm-3.6/lib/libclang-3.6.so')
index = clang.cindex.Index.create()
translation_unit = index.parse(sys.argv[1], ['-x', 'c++', '-std=c++11', '-D__CODE_GENERATOR__'])
print(asciitree.draw_tree(translation_unit.cursor, node_children, print_node))

但是这个测试的最终结果如下:

TRANSLATION_UNIT adlist.c
 +--FUNCTION_DECL listCreate
     +--COMPOUND_STMT 
        +--DECL_STMT 
           +--STRUCT_DECL list
           +--VAR_DECL list
              +--TYPE_REF struct list

显然,最终结果是错误的。有很多代码没有解析。我试图遍历翻译单元,但结果就像树秀一样 - 许多节点都消失了。为什么会这样?有什么方法可以解决这个问题吗?谢谢!

我猜原因是Libclang无法解析malloc()。因为stdlib既没有包含在此代码中,也没有为malloc提供用户定义的定义。

1 个答案:

答案 0 :(得分:1)

解析没有成功完成,可能是因为你遗漏了一些包含路径。

您可以通过打印诊断消息来确认确切的问题。

translation_unit = index.parse(sys.argv[1], args)
for diag in translation_unit.diagnostics:
    print diag