gpt4 book ai didi

C++ libclang : Retrieving cursor from CXSourceLocation returning wrong cursor?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:11:33 27 4
gpt4 key购买 nike

我目前正在使用 libclang 和 C++ 编写一个简单的克隆检测器。

程序使用结构存储游标,包含指向翻译单元的指针和通过调用 clang_getCursorLocation(cursor) 获得的 CXSourceLocation。

typedef struct {
CXTranslationUnit* tu;
CXSourceLocation srcLoc;
} t_cursorLocation;

为了这个错误,子访问者函数访问每个节点并从每个游标创建一个结构。使用 t_cursorLocation 类型的结构,我编写了这个函数来检索相应的光标:

CXCursor getCursor(t_cursorLocation *loc1) {
return clang_getCursor(*loc1->tu, loc1->srcLoc);
}

但是,对于某些游标,当我创建 t_cursorLocation 结构并使用它来检索从中创建的游标时,检索到的游标不等于它的来源游标。例如,查看子访问者函数:

CXChildVisitResult traverseAST(CXCursor cursor, CXCursor parent,
CXClientData client_data) {
CXTranslationUnit tu = clang_Cursor_getTranslationUnit(cursor);
CXTranslationUnit tu2 = *((CXTranslationUnit *) client_data);

t_cursorLocation *loc = new t_cursorLocation();
loc->tu = &tu;
loc->srcLoc = clang_getCursorLocation(cursor);

CXCursor c2 = getCursor(loc);
printf("CursorKind\t%s\n",
clang_getCString(clang_getCursorKindSpelling(cursor.kind)));
if (clang_equalCursors(cursor, c2)) {
printf("Noooo - the cursors do not match! Next test.....");
// use translation unit passed as client_data to see if
// there's a difference
loc->tu = &tu2;
c2 = getCursor(loc);
if (clang_equalCursors(cursor, c2)) {
printf("FAILED ALSO!\n");
} else {
printf("PASSED???\n");
}
} else {
printf("We have a match!\n");
}
return CXChildVisit_Recurse;
}

我的主要功能如下:

int main(int argc, char **argv) {
CXIndex index = clang_createIndex(0, 0);
// initialise the translation unit
CXTranslationUnit tu = clang_parseTranslationUnit(index, 0,
argv, argc, 0, 0, CXTranslationUnit_None);

// set the client data in traverseAST
CXClientData data = &tu;// NULL;
// get the root cursor for the translation unit
CXCursor rootCursor = clang_getTranslationUnitCursor(tu);
clang_visitChildren(rootCursor, traverseAST, data);

clang_disposeTranslationUnit(tu);
clang_disposeIndex(index);

return 0;
}

我运行的虚拟源代码如下:

void goo() {
// nothing here
}

void foo() {
// do something
int a;
switch (a) {
case 0:
goo();
};
}

但是输出是一致的,这表明这只发生在某些游标类型上。

这是一个错误还是我遗漏了什么或做错了什么?

提前致谢,雅各布

最佳答案

要么我完全没有理解您的观点,要么您以错误的方式使用了 clang_equalCursors:当两个游标相等时,clang_equalCursors 返回一个非零值。这意味着我认为您正在测试游标不等式而不是等式。

现在,让我尝试解释为什么某些游标的行为明显不同于其他游标。每个光标只有一个源位置。但是,同一源位置可能有多个游标。例如考虑以下行:

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

上面标记的位置应该至少有两个光标:

  1. VarDecl:索引
  2. DeclRefExpr:index = clang_createIndex(0,0)

当您将源位置转换回游标时,clang_getCursor 会为您提供最具体的一个(在本例中为变量声明)。我怀疑这就是您在这种情况下发生的情况:getCursor(loc) 仅返回您正在访问的光标,前提是它在其位置最具体。

尝试打印每个光标的物理源位置(例如使用 clang_getCursorExtentclang_getExpansionLocation )以了解发生了什么。

关于C++ libclang : Retrieving cursor from CXSourceLocation returning wrong cursor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15346521/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com