无法在include语句中的某些偏移处获得CXCursor

时间:2014-01-08 10:58:35

标签: libclang

将此源​​文件命名为test.cpp

#include <string>

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

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

我希望得到所有偏移0到17的CXCursor_InclusionDirective CXCursor。任何人都可以解释原因吗? (对于使用“”而不是&lt;&gt;的包含语句,似乎不会出现问题)

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;
}

0 个答案:

没有答案