CLang Libtooling: fetching datatype of a variable inside clang::VarDecl, clang::FieldDecl or clang::ParmVarDecl

3.6k Views Asked by At

I am working on CLang 3.5. I am trying to fetch info about variables declared in a C++ project.

How can I fetch datatype or qualified class name of a variable in a clang::VarDecl, clang::FieldDecl or clang::ParmVarDecl object? I tried to find a function which can return datatype or class name of the variable in doc for clang::VarDecl provided here.

http://clang.llvm.org/doxygen/classclang_1_1VarDecl.html

I also tried to look into the code of $LLVM/tools/clang/tools/clang-check/ClangCheck.cpp because on passing cmd arg --ast-dump it shows all of the information about every AST node including all of the variables declared. I wonder how to access all of that information.

I am using ASTMatchers to find my variable declarations, those are:

fieldDecl().bind("field")
parmVarDecl().bind("param")
varDecl().bind("var")

Can anybody please tell me how can I get datatype of all of the variables delcared?

1

There are 1 best solutions below

1
Jason Heo On

Recently, I'm learning Clang and I've wrote some codes after reading this question. It might help you.

Full source code is available in github.com (see ex04.cc)

DeclarationMatcher FieldDeclMatcher =
    clang::ast_matchers::fieldDecl().bind("field_decl");

class LoopPrinter : public MatchFinder::MatchCallback
{
public :
    virtual void run(const MatchFinder::MatchResult& result)
    {
        if (const clang::FieldDecl* fd
            = result.Nodes.getNodeAs<clang::FieldDecl>("field_decl"))
        {
            std::cout << "======== FieldDecl found ======" << std::endl;

            const clang::RecordDecl* rd = fd->getParent();
            const clang::QualType qt = fd->getType();
            const clang::Type* t = qt.getTypePtr();

            std::cout << "FieldDecl found '"
                      << fd->getQualifiedNameAsString() << " "
                      << fd->getName().str() << "' in '"
                      << rd->getName().str() << "'. "
                      << "is Builtintype = " << t->isBuiltinType() << " "
                      << std::endl << std::endl;
        }

    } // end of run()
};