【问题标题】:Parsing C in python with libclang but generated the wrong AST使用 libclang 在 python 中解析 C 但生成了错误的 AST
【发布时间】:2015-12-17 07:43:06
【问题描述】:

我想使用 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 提供用户定义的定义。

【问题讨论】:

    标签: python libclang


    【解决方案1】:

    解析未成功完成,可能是因为您缺少一些包含路径。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-21
      • 2015-04-16
      • 1970-01-01
      相关资源
      最近更新 更多