Niedawno zacząłem używać libclang do parsowania plików C. Problem, który mam, polega na tym, że libclang inicjuje preprocesor przed wygenerowaniem AST. Chciałbym zakazać preprocesor z systemem, a zamiast być podana informacja, że dyrektywy preprocesora są w pliku ...Pobieranie informacji o dyrektywach pre-procesora
używam następujący skrypt Pythona (cindex.py i 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)
Która wyjścia
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;
}
w następnym kod C:
#include <stdio.h>
#define HELLO_WORLD "HELLO!"
int main()
{
printf(HELLO_WORLD);
return 0;
}
Chciałbym uzyskać DEFINE_DECL HELLO_WORLD dla mojego #define w kodzie (obecnie nic nie dostaję). I oczywiście otrzymuję podobne stwierdzenia dla moich # include. czy to możliwe?
EDYCJA: Zasadniczo chcę przeanalizować plik bez rozszerzonej dyrektywy preprocesora.
Jeśli jesteś gotów rozważyć coś innego niż Clang, mam alternatywne rozwiązanie. –