c++ - 如何使用 clang LibTooling 获取函数指针参数名称?

标签 c++ clang llvm libtooling

假设我分析了这样一段代码:

struct Foo
{
    void(*setParam)(const char* name, int value);
};

我使用 clang LibTooling 并在 setParam 上获取 FieldDecl

我想我可以获得这样的参数类型:

auto ft = fieldDecl->getFunctionType()->getAs<FunctionProtoType>();
for (size_t i = 0; i < fpt->getNumParams(); i++)
{
    QualType paramType = fpt->getParamType(i);
    ....
}

但是我如何获得参数名称呢? (在那种情况下是“名称”和“值”)这是否可能,或者我需要手动查看源代码(使用 SourceManager)?

最佳答案

我不认为直接从类型中获取参数名称是可能的,因为它们不是类型信息的一部分。

但是您的任务可以通过再次访问函数指针声明来完成:

class ParmVisitor
    : public RecursiveASTVisitor<ParmVisitor>
{
public:
    bool VisitParmVarDecl(ParmVarDecl *d) {
        if (d->getFunctionScopeDepth() != 0) return true;

        names.push_back(d->getName().str());
        return true;
    }

    std::vector<std::string> names;
};

那么调用站点是:

bool VisitFieldDecl(Decl *d) {
    if (!d->getFunctionType()) {
        // not a function pointer
        return true;
    }
    ParmVisitor pv;
    pv.TraverseDecl(d);
    auto names = std::move(pv.names);

    // now you get the parameter names...

    return true;
}

注意 getFunctionScopeDepth() 部分,这是必要的,因为函数参数本身可能是函数指针,例如:

void(*setParam)(const char* name, int value, void(*evil)(int evil_name, int evil_value));

getFunctionScopeDepth() 为 0 可确保此参数不在嵌套上下文中。

关于c++ - 如何使用 clang LibTooling 获取函数指针参数名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53910964/

相关文章:

c++ - sourceFile 编译器错误 - 常见问题

c++ - 将整个 ASCII 文件读入 C++ std::string

c++ - 链接时 GCC 内存过载

c++ - llvm-ld 仍然存在于 clang 3.4 吗?

c# - 编写一个针对 LLVM 的 C# 编译器是否有意义?

c++ - 什么是资源或指针的所有权?

linker - 有没有办法确保 clang 链接未引用的库符号

CS50 IDE clang : error: linker command failed with exit code 1

debugging - 为什么调试符号在LLVM编译/链接过程中丢失?

c++ - 为什么 switch 只能与 const 值进行比较?