铛发出错误的光标

时间:2019-04-06 11:30:52

标签: c clang

我编写了确定光标下实例类型的程序。

#include <stdio.h>
#include <stdlib.h>
#include <clang-c/Index.h>

int main(int argc, char *argv[])
{
    CXIndex index;
    CXTranslationUnit tu;
    CXFile file;
    CXSourceLocation loc;
    CXCursor cursor, def;
    CXType type;
    CXString typesp;
    const char *types;

    index = clang_createIndex(0, 0);
    tu = clang_createTranslationUnitFromSourceFile(index, argv[1],
            0, NULL, 0, NULL);
    file = clang_getFile(tu, argv[1]);
    loc = clang_getLocation(tu, file, atoi(argv[2]), atoi(argv[3]));
    cursor = clang_getCursor(tu, loc);

/* Cursor location check */
CXSourceLocation testloc;
testloc = clang_getCursorLocation(cursor);
unsigned lnum, colnum;
clang_getFileLocation(testloc, NULL, &lnum, &colnum, NULL);
printf("%d %d\n", lnum, colnum);

    if (clang_isPreprocessing(cursor.kind))
        printf("Preprocessor\n");
    else {
        def = clang_getCursorDefinition(cursor);
        if (clang_Cursor_isNull(def))
            type = clang_getCursorType(cursor);
        else 
            type = clang_getCursorType(def);
        typesp = clang_getTypeSpelling(type);
        types = clang_getCString(typesp);
        printf("%s\n", types);
        clang_disposeString(typesp);
    }
    clang_disposeTranslationUnit(tu);
    clang_disposeIndex(index);
}

当我通过16(行)和3(列)参数将程序应用于自身的源代码时

    index = clang_createIndex(0, 0);
//   ^

它显示对应的6(行)和1(列)

int main(int argc, char *argv[])
{
^

错了。但是当应用28 3对应时

printf("%d %d\n", lnum, colnum);
//^

它显示28 1,它是正确的。为什么在第一种情况下将游标设置为错误,以及如何将其设置为正确?

UPD:

我发现一个错误的解决方案:在主程序启动之前用clang -emit-ast生成ast文件,并用clang_createTranslationUnit()从ast文件中创建TranslationUnit。理论上lang_createTranslationUnitFromSourceFile应该对源文件执行与clang_createTranslationUnit()对ast文件相同的操作,不是吗?我的意思是从这两个函数获得的TranslationUnits应该相同。我错了吗?

0 个答案:

没有答案