在libclang中获取类型不合格的版本

Getting unqualified version of Type in libclang

本文关键字:不合格 版本 取类型 获取 libclang      更新时间:2023-10-16

是否有一种方法可以获取"基本"类型的 Type。我看到可以测试constvolatile,但我看不出方法来获取基础类型。

我最终试图做的是映射类之间的成员关系,目前由于类型Aconst A的不同而缺少。

我看到的唯一解决方法是与clang_isConstQualifiedType和解析拼写检查,这似乎不是一个好主意。

这是我有问题的类布局:

class A {};
class B {
 A a;
}
class C {
  const A a;
  B* b;
}

很难映射C->A

它至少一个部分解决方案在于函数" clang_gettypedeclaration"。希望这应该指向您正确的方向,但是我会发布一些我的代码和我得到的结果。

// clang_fullname.cc
#include <clang-c/Index.h>
#include <iostream>
using namespace std;
/*
 * help with CXString
 */
ostream &operator<<(ostream &o, CXString cxs) {
  o << clang_getCString(cxs);
  clang_disposeString(cxs);
  return o;
}
/*
 * Display fully qualified cursor name
 */
ostream &operator<<(ostream &o, CXCursor cursor) {
  /*
   * Base of recursion
   */
  if (clang_Cursor_isNull(cursor) || clang_isTranslationUnit(cursor.kind))
    return o;
  /*
   * switching to a referenced cursor is nice for templates and function calls
   */
  CXCursor cursorReferenced = clang_getCursorReferenced(cursor);
  /*
   * Sometimes a cursorReferenced will be the same cursor, so we must avoid
   * infinite recursion
   */
  if (!clang_Cursor_isNull(cursorReferenced) &&
      !clang_equalCursors(cursor, cursorReferenced)) {
    return o << clang_getCursorReferenced(cursor);
  } else {
    /*
     * Typical recursive step
     */
    return o << clang_getCursorSemanticParent(cursor)
             << "::"
             /*
              * Here the type of the type declaration is retrieved #ugly
              */
             << clang_getTypeSpelling(clang_getCursorType(
                    clang_getTypeDeclaration(clang_getCursorType(cursor))));
  }
}
int main(int argc, char *argv[]) {
  if (argc != 4) {
    cout << "usage: filename line col" << endl;
    return 0;
  }
  CXIndex index = clang_createIndex(0, 0);
  CXTranslationUnit TU = clang_createTranslationUnitFromSourceFile(
      index, argv[1], 0, nullptr, 0, nullptr);
  CXFile cxfile = clang_getFile(TU, argv[1]);
  unsigned line = atoi(argv[2]);
  unsigned column = atoi(argv[3]);
  CXSourceLocation cxloc = clang_getLocation(TU, cxfile, line, column);
  cout << clang_getCursor(TU, cxloc) << endl;
  clang_disposeTranslationUnit(TU);
  clang_disposeIndex(index);
}

因此,程序采用文件名,行号和列,并输出确定的类型。我使用了以下测试文件:

//foo.cc
class A {};
class B {
  A a;
}
class C {
  const A a;
  B *b;
}

并运行以下命令:

./clang_fullname foo.cc 10 5

(这指向" const"中的" n"(

并作为输出:

::C::A

我在其他一些事情上进行了测试,这似乎是一个"可行的解决方案",当然,我比试图手动"解析" const预选赛更有信心。

注意:上面写的方式有些危险。因为cxcursor只是void*的打字机,该运算符&lt;&lt;将吞噬所有无效的指针。最好将Cxcursor包装在某些辅助类别中。