首页 > 解决方案 > libclang 为类型限定符给出错误的结果

问题描述

Currentlty 我正在做一个项目,用 libclang 转储 c++ 代码的类信息。还有一些关于类型限定符的悲惨经历:const、volatile、&、&& 及其组合。以下是转储函数 delearation 的参数类型的示例代码。

auto _cur_cursor = one_node->get_cursor();
auto _cur_type = clang_getCursorType(_cur_cursor);
auto is_const = clang_isConstQualifiedType(_cur_type);
auto is_refer = clang_Type_getCXXRefQualifier(_cur_type);
auto is_volatile = clang_isVolatileQualifiedType(_cur_type);
auto is_pointer = clang_getPointeeType(_cur_type);
auto is_const_ref = false;
if (is_pointer.kind)
{
    is_const_ref = clang_isConstQualifiedType(is_pointer);
}
the_logger.info("get parameter name {} type {} is_const {} is_reference {} is volatile {} is_pointer {} is_const_ref {}", utils::to_string(clang_getCursorSpelling(_cur_cursor)), utils::to_string(clang_getTypeSpelling(_cur_type)), is_const, is_refer, is_volatile, utils::to_string(is_pointer), is_const_ref);

我的测试用例如下

int test_1(const std::vector<std::unordered_map<int, int>>&  a,  std::vector<int>&& b, std::vector<std::uint32_t>& c)
{
    return b.size();
}

这个函数的输出是

[2019-06-01 23:14:18.171] [meta] [info] get parameter name a type const std::vector<std::unordered_map<int, int> > & is_const 0 is_reference 0 is volatile 0 is_pointer const std::vector<std::unordered_map<int, int> > is_const_ref true
[2019-06-01 23:14:18.171] [meta] [info] get parameter name b type std::vector<int> && is_const 0 is_reference 0 is volatile 0 is_pointer std::vector<int> is_const_ref false
[2019-06-01 23:14:18.171] [meta] [info] get parameter name c type std::vector<std::uint32_t> & is_const 0 is_reference 0 is volatile 0 is_pointer std::vector<std::uint32_t> is_const_ref false

这些观察结果对我来说是可疑的:

  1. clang_isConstQualifiedType 只为 const T 返回 true,而不是为 const T (&, *, &&)
  2. clang_Type_getCXXRefQualifier 对于任何类型始终为 false
  3. clang_getPointeeType 为 T( ,&, &&) 返回 T,为 const T( , &, &&)返回 const T

这些 api 似乎没有按预期运行。有什么想法可以为 CXType 获得正确的 const 引用 volatile 限定符状态?

标签: c++clangllvm-clanglibclang

解决方案


  1. 和 3.const T (&, *, &&)确实不是const限定类型,它是限定类型的(引用、指针、r 值引用)constconst T * const将是一个限定类型的const限定指针。您可以查看cppreference以获取更多详细信息。constT

  2. 来自 libclang 的文档

检索函数或方法的 ref-qualifier 类型。

为 C++ 函数或方法返回 ref 限定符。对于其他类型或非 C++ 声明,返回 CXRefQualifier_None。

可能,您正在寻找其他东西。检查CXType::kind_cur_type.kind在您的代码段中)是否有CXType_Pointer,CXType_LValueReferenceCXType_RValueReference不是。

我希望这很有用。愉快的铿锵黑客!


推荐阅读