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

前回から少し時間があきました。
前回は definition に関する記事を書きました。
今回は referenced について書きます。
referenced は前回紹介した definition と似ており定義位置を返します。
definition との違いは definition が宣言のみの場合は None を返すのに対し、referenced の場合は宣言位置を返します。

[ソース]

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

Config.set_compatibility_check(False)
Config.set_library_path("D:/LLVM/BUILD_3_3/bin")


# source code
source = """\

// 宣言のみの関数
void
func1();

// 先に宣言し、後から定義する関数
void
func2(int);

// 定義のみの関数
void
func3(int, float){

}

// func2() の定義
void
func2(int){

}

int
main(){
    func1();
    func2(1);
    func3(1, 3.31f);
    return;
}
"""

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)


# Cursor の情報を出力
def print_cursor(cursor):
    if cursor is None:
        print "None"
        return
    print "displayname: %s" % cursor.displayname
    print "spelling   : %s" % cursor.spelling
    print "kind       : %s" % cursor.kind
    print "location   : %s" % cursor.location

def1 = make_cursor("test.cpp", 24, 2)
print "-------- referenced func1() --------"
print_cursor(def1.referenced)

print ""

def2 = make_cursor("test.cpp", 25, 2)
print "-------- referenced func2() --------"
print_cursor(def2.referenced)

print ""

def3 = make_cursor("test.cpp", 26, 2)
print "-------- referenced func3() --------"
print_cursor(def3.referenced)

[出力]

-------- referenced func1() --------
displayname: func1()
spelling   : func1
kind       : CursorKind.FUNCTION_DECL
location   : <SourceLocation file 'test.cpp', line 4, column 1>

-------- referenced func2() --------
displayname: func2(int)
spelling   : func2
kind       : CursorKind.FUNCTION_DECL
location   : <SourceLocation file 'test.cpp', line 18, column 1>

-------- referenced func3() --------
displayname: func3(int, float)
spelling   : func3
kind       : CursorKind.FUNCTION_DECL
location   : <SourceLocation file 'test.cpp', line 12, column 1>


こんな感じです。
と、書いておいてあれなんですが、具体的な仕様を把握していないのでもしかしたら認識が間違っているかも…。
次こそは型情報について書く予定。

[Clang]

  • clang++ (LLVM) 3.3