检索有关预处理器指令的信息

检索有关预处理器指令的信息

本文介绍了检索有关预处理器指令的信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始使用 libclang 来解析 C 文件.我遇到的问题显然是,libclang 在生成 AST 之前启动了预处理器.我想禁止预处理器运行,而是提供预处理器指令在文件中的信息...

I've recently started using libclang to parse C files. The problem I'm having is that apparently, libclang initiates the preprocessor before generating AST. I would like to prohibit the preprocessor from running, and instead be given information that preprocessor directives are in the file...

我使用以下 python 脚本(cindex.py 和 libclang)

I use the following python script (cindex.py and 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 也会得到类似的声明.这可能吗?

What I would like is to get DEFINE_DECL HELLO_WORLD for my #define in the code (currently I get nothing). And of course also get similar statements for my #include's. Is this possible?

基本上,我想在不扩展预处理器指令的情况下解析文件.

Basically, I want to parse the file without preprocessor directives expanded.

推荐答案

几天前我在 #llvm freenode irc 频道上问过同样的问题.答案是宏不是 AST 的一部分,所以你不能",但很可能-fsyntax-only"选项和 clang 插件而不是 libclang 可以帮助你.

A few days ago I have asked the same question on the #llvm freenode irc channel. The answer was "macroses is not part of AST, so you can't", but most probably "-fsyntax-only" option and clang plugin instead of libclang may help you.

看起来现在实际上是可能的,请参阅 bradtgmurray 的答案

Edited: Looks like now it is actually possible, see answer by bradtgmurray

这篇关于检索有关预处理器指令的信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 18:13