libclang の Python binding を使用する 〜 Type 編〜

前回からすっかり時間があいてしまいましたがまだ続けますよ。
決して忘れていたわけではない
前回までは Cursor について書いていましたが、今回は型情報について簡単に書きます。
Cursor からその位置の型情報を取得する事ができます。

[ソース]

# -*- coding: utf-8 -*
import clang.cindex
from clang.cindex import Cursor


# source code
source = """
int value;
value = 0;

int* ptr;
ptr = &value;

struct X{};
X x;
x;
"""

index = clang.cindex.Index.create()

tu = index.parse("test.cpp", unsaved_files = [ ("test.cpp", source)])

# Cursor の生成
def make_cursor(file, line, col):
    # location を定義
    location = tu.get_location(file, (line, col))
    
    # location からその位置の cursor を取得
    return Cursor.from_location(tu, location)

# Type の情報を出力
def print_type(type):
    print "kind : %s" % type.kind


cursor1 = make_cursor("test.cpp", 2, 1)
print_type(cursor1.type)

cursor2 = make_cursor("test.cpp", 5, 1)
print_type(cursor2.type)

cursor3 = make_cursor("test.cpp", 9, 1)
print_type(cursor3.type)

[出力]

kind : TypeKind.INT
kind : TypeKind.POINTER
kind : TypeKind.RECORD


任意の位置の型情報を取得する場合は、まずその位置の Cursor を生成して、その Cursor から型情報の取得を行います。
次は型情報から型名を取得する方法について書く予定。

[Clang]

  • clang++ (LLVM) 3.3