2014-01-30 12 views
1

當使用libclang時,如何從stdio.h中排除函數?在libclang中如何從stdio.h中排除函數

當我使用下面的源只收集函數定義,然後我最終從stdio.h獲得所有的函數。

我讀過,我們可以在創建索引時傳遞'-x c-header'類型的參數。但是,這種方式是否適用於libclang?

tu = index.parse(self.filename, "-x c-header") 

包括「C-頭」參數後,將其要我填「unsaved_files」陣列爲好,如在每「cindex.py」「解析」函數的定義。

def parse(self, path, args = [], unsaved_files = [], options = 0): 

我不知道什麼是正確的方法來做到這一點。

def funcdefn_visitor(self, node, parent, userdata): 
    if node.kind == clang.cindex.CursorKind.FUNCTION_DECL: #gives function definitions 
     self.func_defn.append(clang.cindex.Cursor_displayname(node)) 
     self.func_defn_line_no.append(node.location.line) 
     self.func_defn_col_no.append(node.location.column) 
    print 'Found %s [line=%s, col=%s]' % (
     clang.cindex.Cursor_displayname(node), 
     node.location.line, 
     node.location.column) 
    return 2 # means continue visiting recursively 

index = clang.cindex.Index.create() 

tu = index.parse(self.filename) 
#-- link cursor visitor to call back to give function definitions 
clang.cindex.Cursor_visit(
    tu.cursor, 
    clang.cindex.Cursor_visit_callback(self.funcdefn_visitor), 
    None) 

回答

1

-x c-header命令行開關被用來產生precompiled headers,不從轉換單元排除頭。

我認爲從特定文件中排除函數的正確方法是在訪問AST時跳過位於其中的所有節點。爲了詳細說明你的例子,這個想法是在訪問者中做第一次測試,儘早跳過這個文件,並避免訪問它的所有子節點。

def funcdefn_visitor(self, node, parent, userdata): 

    # You might want to change the test here 
    if node.location.file.endswith("/stdio.h"): 
     print "Skipping 'stdio.h'" 
     # Continue with next sibling 
     return 1 

    if node.kind == clang.cindex.CursorKind.FUNCTION_DECL: #gives function definitions 
     self.func_defn.append(clang.cindex.Cursor_displayname(node)) 
     self.func_defn_line_no.append(node.location.line) 
     self.func_defn_col_no.append(node.location.column) 

    print 'Found %s [line=%s, col=%s]' % (
     clang.cindex.Cursor_displayname(node), 
     node.location.line, 
     node.location.column) 

    # Continue visiting recursively 
    return 2 

index = clang.cindex.Index.create() 

tu = index.parse(self.filename) 
#-- link cursor visitor to call back to give function definitions 
clang.cindex.Cursor_visit(
    tu.cursor, 
    clang.cindex.Cursor_visit_callback(self.funcdefn_visitor), 
    None) 

現在我不cindex.pylibclang的蟒蛇API)的專家,但我認爲你的例子如下C API的概念,而不是蟒蛇的。從文檔引用(重點是我的):

此模塊提供了一個Clang索引庫的接口。這是一個 低級別的索引庫接口,它試圖直接匹配Clang API,同時也是「pythonic」。從C API 顯着的差異是:

  • 字符串返回的結果採用Python字符串,不CXString對象。

  • 將null遊標轉換爲無。

  • 訪問子游標是通過迭代而不是訪問來完成的。

雖然cindex.py結合Cursor_visitclang_visitChildren,它甚至不出口CXChildVisitResult枚舉,這意味着需要硬編碼值BreakContinueRecurse。做事的pythonic方式包括迭代子節點,如Cursor.get_children()方法所返回的那樣。在這些SO回答中給出了一個例子(12),您可以根據源文件自適應篩選節點。