clangでAST変換
AST変換して解析をしているのだが上手くいかない。 関数の引数で渡している DATA_MAX の値が Cursor等のオブジェクトのどの情報を見ても入ってない。 コマンドラインでは入っているので解析されてないわけでは無さそう。。。
# -*- coding:sjis -*- import unittest from pprint import pprint from clang.cindex import * def get_diag_info(diag): return {'severity': diag.severity, 'location': diag.location, 'spelling': diag.spelling, 'ranges': diag.ranges, 'fixits': diag.fixits } def get_cursor_id(cursor, cursor_list=[]): if cursor is None: return None # FIXME: This is really slow. It would be nice if the index API exposed # something that let us hash cursors. for i, c in enumerate(cursor_list): if cursor == c: return i cursor_list.append(cursor) return len(cursor_list) - 1 def get_token(node): LITERAL_KIND = \ ( CursorKind.INTEGER_LITERAL, CursorKind.IMAGINARY_LITERAL, CursorKind.FLOATING_LITERAL, CursorKind.STRING_LITERAL, CursorKind.CHARACTER_LITERAL, ) if node.kind in LITERAL_KIND: tokens = list(node.get_tokens()) result = [x.spelling for x in tokens] else: result = [] return ','.join(result) def get_info(node, depth=0): children = [get_info(c, depth + 1) for c in node.get_children()] return {'id': get_cursor_id(node), 'kind': node.kind, 'usr': node.get_usr(), 'spelling': node.spelling, 'location': node.location, 'extent.start': node.extent.start, 'extent.end': node.extent.end, 'is_definition': node.is_definition(), 'definition id': get_cursor_id(node.get_definition()), 'children': children, 'token': get_token(node), } class Test(unittest.TestCase): def testTest1(self): data = \ """ #define DATA_MAX 0x1234 int calc(unsigned size) { return size % 100; } int main(void) { int p; p = calc( DATA_MAX*sizeof(int) ); return 0; } """ index = Index.create() tu = index.parse("test.c", unsaved_files=[("test.c", data)]) self.assertIsNotNone(tu) pprint(('diags', map(get_diag_info, tu.diagnostics))) pprint(('nodes', get_info(tu.cursor))) if __name__ == "__main__": # import sys;sys.argv = ['', 'Test.testTest1'] unittest.main()