铛-获取SubstTemplateTypeParm完整的模板信息

时间:2019-07-04 21:23:01

标签: c++ windows clang llvm-clang

我正在遍历CAST AST,但是遍历包含clang :: SubstTemplateTypeParmType的AST声明的类型信息时遇到麻烦。

将以下最少的输入代码提供给clang工具

ParameterMap

通过Map的类型递归时,clang表示第一个String参数arg clang::SubstTemplateTypeParmTypeString。如果我尝试通过递归或获取替换类型(下面的代码)来进一步递归以获得有关Type::Record的更多信息,则基础类型为std::basic_string,并且为basic_string<const char*, std::char_traits<const char*>, std::allocator<const char*>>。这对我来说是意外的,因为我希望基础类型是模板特化,例如std::basic_string。由于该节点是一条记录,因此我可以知道该映射包含一个basic_string,但是无法获取basic_string的模板信息。在这种情况下如何获得case Type::SubstTemplateTypeParm: { auto substTemplateType = qualType->getAs<SubstTemplateTypeParmType>(); walkType(substTemplateType->getReplacementType()); return; } 的模板专业化信息?

[
{"directory":"F:/git/minRepro/","command":"\"C:/Program Files (x86)/compilers/clang.exe\" -Wall -isystem -g -std=c++14 -Wno-format -Wno-unneeded-internal-declaration -Werror F:/git/minRepro/exampleSource.cpp","file":"F:/git/minRepro/exampleSource.cpp"}
]

我了解以下要求发布最小可运行代码示例的要求。但是,这需要一个clang工具依赖项,因为它没有预构建,因此插入和运行起来并不容易。

路径是硬编码的,因此需要根据本地设置进行更新。这是compile_commands文件,该文件还有3个要更新的路径。编译器路径,最后两次是文件路径。

#pragma comment(lib,"Version.lib")

#include <clang/Tooling/JSONCompilationDatabase.h>
#include <clang/Tooling/Tooling.h>
#include <clang/Frontend/FrontendAction.h>
#include <clang/Sema/SemaConsumer.h>
#include <clang/AST/Type.h>
#include <clang/AST/TemplateName.h>
#include <clang/AST/Decl.h>
#include <clang/AST/DeclTemplate.h>
#include <clang/Frontend/CompilerInstance.h>

#include <iostream>
#include <cstdlib>
#include <cassert>
#include <vector>
#include <string>

class AstWalker : public clang::SemaConsumer
{
public:
    AstWalker(clang::ASTContext& context)
        : m_context(context)
    {}

    virtual void HandleTranslationUnit(clang::ASTContext& context)
    {
        using namespace clang;

        for (auto declaration : context.getTranslationUnitDecl()->decls())
        {
            const auto&sm = m_context.getSourceManager();

            if (!declaration->getBeginLoc().isValid())
                continue;

            // Only walk declarations from our file.
            if (!sm.isInMainFile(sm.getSpellingLoc(declaration->getBeginLoc())))
                continue;

            // Find functions, and inspect their return type.
            auto nodeKind = declaration->getKind();
            if (nodeKind == Decl::Function)
            {
                auto funcDecl = cast<FunctionDecl>(declaration);

                // Check for and ignore built-in functions.
                if (funcDecl->getBuiltinID() != 0)
                    break;

                walkType(funcDecl->getReturnType());
                break;
            }
        }
    }

    void walkType(const clang::QualType& qualType)
    {
        using namespace clang;

        auto classType = qualType->getTypeClass();
        switch (classType)
        {
        case Type::Typedef:
        {
            auto typedefType = qualType->getAs<TypedefType>();
            walkType(typedefType->desugar());
            return;
        }
        case Type::TemplateSpecialization:
        {
            auto templateSpecialization = qualType->getAs<TemplateSpecializationType>();
            if (templateSpecialization->isTypeAlias())
            {
                walkType(templateSpecialization->getAliasedType());
                return;
            }

            std::string templateType = templateSpecialization->getTemplateName().getAsTemplateDecl()->getQualifiedNameAsString();
            std::cout << templateType << "<";

            auto numArgs = templateSpecialization->getNumArgs();
            for (unsigned int i = 0; i < numArgs; ++i)
            {
                if (i > 0)
                    std::cout << ", ";

                const clang::TemplateArgument& templateArg = templateSpecialization->getArg(i);
                if (templateArg.getKind() == clang::TemplateArgument::ArgKind::Type)
                {
                    walkType(templateArg.getAsType());
                }
            }

            std::cout << ">";
            return;
        }
        case Type::Record:
        {
            const auto record = qualType->getAs<RecordType>();
            std::string recordQualifiedName = record->getAsRecordDecl()->getQualifiedNameAsString();
            std::cout << recordQualifiedName;
            return;
        }
        case Type::Elaborated:
        {
            auto elaboratedType = qualType->getAs<ElaboratedType>();
            walkType(elaboratedType->desugar());
            return;
        }
        case Type::SubstTemplateTypeParm:
        {
            auto substTemplateType = qualType->getAs<SubstTemplateTypeParmType>();
            walkType(substTemplateType->desugar());
            //Also tried getReplacementType.
            //walkType(substTemplateType->getReplacementType());
            return;
        }
        }
    }

private:
    clang::ASTContext& m_context;
};

class ExampleAction : public clang::ASTFrontendAction
{
public:
    ExampleAction() {}

    virtual std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(clang::CompilerInstance& compiler, llvm::StringRef inFile)
    {
        return std::unique_ptr<clang::ASTConsumer>(new AstWalker(compiler.getASTContext()));
    }
};

int main(int argc, char **argv)
{
    // Create the compilation database.
    std::string errorOut;
    std::unique_ptr<clang::tooling::JSONCompilationDatabase> compilationDatabase = clang::tooling::JSONCompilationDatabase::loadFromFile("F:/git/minRepro/compile_commands.json", errorOut, clang::tooling::JSONCommandLineSyntax::AutoDetect);

    if (compilationDatabase == nullptr || !errorOut.empty())
    {
        std::cout << "[Error] Failed to load compilation database. Error=" << errorOut.c_str() << std::endl;
        return false;
    }

    std::vector<std::string> headerFiles;
    headerFiles.push_back("F:/git/minRepro/exampleSource.cpp");
    clang::tooling::ClangTool tool(*compilationDatabase, llvm::ArrayRef<std::string>(headerFiles));

    auto toolResult = tool.run(clang::tooling::newFrontendActionFactory<ExampleAction>().get());
    if (toolResult == 1)
    {
        std::cout << "[Error] Error occurred.  Check log.  Aborting.\n";
        assert(false);
        return false;
    }
}

代码:

wp-content/uploads

1 个答案:

答案 0 :(得分:1)

在某些情况下,模板信息嵌套在给定ClassTemplateSpecializationDecl的{​​{1}}中。您可以通过将RecordType转换为RecordDecl来阅读它。

ClassTemplateSpecializationDecl