2

鉴于此源文件为 test.cpp

#include <string>

如果我使用 clang_parseTranslationUnit() 使用 CXTranslationUnit_DetailedPreprocessingRecord 选项对其进行解析,我发现我的源文件中有一个 CXCursor,类型为 CXCursor_InclusionDirective,偏移量为 0 到偏移量 17。

如果我通过调用 clang_getLocationForOffset() 和 clang_getCursor() 获得一个 CXCursor 偏移量 0 到 9 我得到这个光标。对于偏移量 10 到 17,我得到一个 CXCursor 类型为 CXCursor_NoDeclFound。

我希望获得所有偏移量 0 到 17 的 CXCursor_InclusionDirective CXCursor。谁能解释为什么?(对于使用“”而不是 <> 的包含语句,问题似乎没有发生)

CXCursor GetCursotAt(CXTranslationUnit tu, CXFile file, unsigned offset)
{
    CXSourceLocation sl;
    sl = clang_getLocationForOffset(tu, file, offset);
    assert(!clang_equalLocations(sl, clang_getNullLocation()));
    return clang_getCursor(tu, sl); 
}

void GetCursorExtentOffsets(CXCursor cursor, unsigned* start, unsigned* end)
{
    CXSourceRange range = clang_getCursorExtent(cursor);
    CXSourceLocation loc;
    CXFile f;
    unsigned l, c, o;

    loc = clang_getRangeStart(range);   
    clang_getInstantiationLocation(loc, &f, &l, &c, &o);
    *start = o;

    loc = clang_getRangeEnd(range);
    clang_getInstantiationLocation(loc, &f, &l, &c, &o);
    *end = o;   
}

int main(int argc, const char **argv) 
{
    CXIndex idx = clang_createIndex(1, 0);
    CXTranslationUnit tu = clang_parseTranslationUnit(idx, "test.cpp", NULL, 0, NULL, 0, CXTranslationUnit_DetailedPreprocessingRecord);
    assert(tu);
    CXFile file = clang_getFile(tu, "test.cpp");
    assert(file);

    CXCursor c;
    unsigned start, end;
    unsigned testOffset;

    //Check Curosr at offset 0
    testOffset = 0;
    c = GetCursotAt(tu, file, testOffset);
    assert(!clang_equalCursors(c, clang_getNullCursor()));
    //check we have a cursor for the #include
    assert(clang_getCursorKind(c) == CXCursor_InclusionDirective);
    //check cursor covers entire range (0 -> 17)
    GetCursorExtentOffsets(c, &start, &end);
    assert(start == 0);
    assert(end == 17);

    //Check Cursor returned for offsets 1,2,3...9
    for(testOffset = 1; testOffset < 10; testOffset++)
    {
        c = GetCursotAt(tu, file, testOffset);
        assert(!clang_equalCursors(c, clang_getNullCursor()));
        //check we have a cursor for the #include
        assert(clang_getCursorKind(c) == CXCursor_InclusionDirective);
    }

    //Check Cursor at offset 9,10...17. All will return a CXCursor with kind CXCursor_NoDeclFound
    for(testOffset = 10; testOffset < 17; testOffset++)
    {
        c = GetCursotAt(tu, file, 10);
        assert(!clang_equalCursors(c, clang_getNullCursor()));
        //check we have a cursor for the #include
        //!!clang_getCursorKind(c) now returns CXCursor_NoDeclFound!!
        assert(clang_getCursorKind(c) == CXCursor_NoDeclFound);
    }
    return 0;
}
4

0 回答 0