Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clang - Getting SubstTemplateTypeParm full template information

I am traversing a clang AST, but am having trouble getting the desired information when traversing the type information of a declaration of the AST that contains a clang::SubstTemplateTypeParmType.

Given the following minimal input code to clang tooling

#include <map>

template <typename K, typename V> using Map = std::map<K, V>;
using String = std::string;
using ParameterMap = Map<String, String>;

ParameterMap someFunc();

When recursing through ParameterMap's type, clang says that the first Map parameter arg, String, is a clang::SubstTemplateTypeParmType. If I try to recurse further to get more info about String, by either desugaring, or getting the replacement type (code below), the underlying type is of Type::Record, and is std::basic_string. This is unexpected for me, as I would expect the underlying type to be a template specialization, something like basic_string<const char*, std::char_traits<const char*>, std::allocator<const char*>>. Since the node is a record, I can get that the map contains a std::basic_string, but cannot get the template information of basic_string. How can I get the template specialization information of basic_string in such a case?

case Type::SubstTemplateTypeParm:
{
    auto substTemplateType = qualType->getAs<SubstTemplateTypeParmType>();
    walkType(substTemplateType->getReplacementType());
    return;
}

I understand the requirement of posting a minimal runnable code example, which is below. However this requires a clang tooling dependency, for which there are no pre-builts, so this is not so easy to plug and run.

The paths are hard coded so need to be updated based on your local setup. Here is the compile_commands file, which also has 3 paths to update. The compiler path, and the file path at the end twice.

[
{"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"}
]

Code:

#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;
    }
}
like image 581
Justin Avatar asked Jul 04 '19 21:07

Justin


1 Answers

In some cases, the template information is nested within ClassTemplateSpecializationDecl for a given RecordType. You can read it by casting your RecordDecl into a ClassTemplateSpecializationDecl.

const auto record = qualType->getAs<clang::RecordType>();
auto classTemplateSpecialization = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(record->getAsRecordDecl());
if (classTemplateSpecialization)
{
    const auto& args = classTemplateSpecialization->getTemplateArgs();
    for (unsigned int i = 0; i < args.size(); ++i)
    {
        const clang::TemplateArgument& templateArg = args[i];
        // Read arg info as needed.
    }   
}
else
{
    // Not a template specialization.
}
like image 126
Justin Avatar answered Dec 14 '22 20:12

Justin