lvxuzhou


私信TA

用户名:lvxuzhou

访问量:95871

签 名:

lvxuzhou

等  级
排  名 47
经  验 11032
参赛次数 0
文章发表 56
年  龄 0
在职情况 学生
学  校 西安
专  业

  自我简介:

环境:win7 64位+llvm11+mingw+python3.7+libclang11

基于libclang写了一个提取C语言宏定义的工具

C语言测试代码:

#ifndef DEFAULT_PORT
#define DEFAULT_PORT "80"             /* Default TCP port for HTTP */
#endif
#ifndef MAX_CONTENT_LENGTH
#define MAX_CONTENT_LENGTH 250000000  /* Max length of HTTP request content */
#endif
#ifndef MAX_CPU
#define MAX_CPU 30                /* Max CPU cycles in seconds */
#endif
#define MULTIPLY(x, y) x * y
#define foo(x)  { bar(x); baz(x); }
#define PR(...) printf(__VA_ARGS_)
#define MacroLog(...)\
{\
    FILE* file;\
    fopen_s(&file,"./a.txt","a");\
    if (file != nullptr)\
    {\
        fprintf(file, "%s: Line %d:\t", __FILE__, __LINE__);\
        fprintf(file, __VA_ARGS__);\
        fprintf(file, "\n");\
    }\
    fclose(file);\
}

python代码

from clang.cindex import Config #配置
from clang.cindex import TypeKind
from clang.cindex import CursorKind
from clang.cindex import Index #主要API
from clang.cindex import Token
from clang.cindex import TranslationUnit

def GetTranslationUnit(filename):
    index = Index.create()
    tu = index.parse(filename,options=TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD)
    print("tTranslation Unit=%s"%(tu.spelling))
    return tu
def LoadLibClang(libclangPath):
    if Config.loaded == True:
        pass
    else:
        Config.set_library_file(libclangPath)
def GetDefineStr(node):
    start_row=node.extent.start.line
    end_row = node.extent.end.line

    with open(node.location.file.name,encoding='utf-8',errors='ignore') as file:
        lines=file.readlines()
        retStr=''
        loop=start_row-1
        while loop<end_row:
            retStr+=lines[loop]
            loop+=1
        print(retStr,end='')


#主函数
if __name__ == '__main__':
    filename='althttpd.c' # C语言文件
    libclangPath = r'C:\Program Files\LLVM\bin\libclang.dll' #libclang库路径
    LoadLibClang(libclangPath) #加载libclang库
    tu=GetTranslationUnit(filename)#解析main.c
    ast_root_node=tu.cursor #获取cursor根节点
    print(tu.spelling)
    functionList=[]
    print("Print all nodes in ast tree:")
    for node in ast_root_node.walk_preorder():  # 遍历词法分析结果
        # if node.kind==CursorKind.MACRO_DEFINITION STRUCT_DECL TYPEDEF_DECL CALL_EXPR:
        if node.kind == CursorKind.MACRO_DEFINITION:
            if str(node.location.file) ==tu.spelling:
                GetDefineStr(node)

运行结果:

QQ图片20211005222127.png

 

0.0分

0 人评分

  评论区