我最近开始使用libclang来解析C文件.我遇到的问题是,显然,libclang会在生成AST之前启动预处理程序.我想禁止预处理器运行,而是提供预处理指令在文件中的信息…
我使用以下python脚本(cindex.py和libclang)
import codecs from clang.cindex import * class SourceFile(object): def __init__(self,path): with codecs.open(path,'r','utf-8') as file: self.file_content = file.read() index = Index.create() root_node = index.parse(path) for included in root_node.get_includes(): print included.include self.print_declerations(root_node.cursor) def print_declerations(self,root,recurse=True): print root.kind.name,root.spelling if root.kind.is_declaration(): node_def = root.get_definition() if node_def is not None: start_offset = node_def.extent.start.offset end_offset = node_def.extent.end.offset + 1 print self.file_content[start_offset:end_offset],'\n' if recurse: for child in root.get_children(): self.print_declerations(child,False) if __name__ == '__main__': path = 'Sample.cpp' print 'Translation unit:',path source = SourceFile(path)
哪些输出
Translation unit: Sample.cpp /mingw/include\stdio.h /mingw/include\_mingw.h /mingw/include\sys/types.h TRANSLATION_UNIT None TYPEDEF_DECL __builtin_va_list STRUCT_DECL _iobuf TYPEDEF_DECL FILE VAR_DECL _iob UNEXPOSED_DECL FUNCTION_DECL main int main() { printf(HELLO_WORLD); return 0; }
对于以下C代码:
#include <stdio.h> #define HELLO_WORLD "HELLO!" int main() { printf(HELLO_WORLD); return 0; }
我想要的是在代码中为我的#define获取DEFINE_DECL HELLO_WORLD(目前我什么都没有).当然也可以得到类似的我的#include的声明.这可能吗?
编辑:基本上,我想解析文件,而不扩展预处理指令.