Search code examples
clangllvm-clang

How to get the type of an expression as a string?


I'm having a small problem here. I have a clang::Expr object. I want to get the type of that expression as a string. According to the documentation, clang::Expr returns a QualType. clang::QualType has a method called getAsString() which returns a string describing that type.

// Get the expressions to the left and right of the binary operator.
const Expr *lhs = binop->getLHS()->IgnoreParenCasts();
string typeLhs = lhs->getType()->getAsString();

When I type make, it reports an error:

remove_memcpy.cpp:110:46: error: no member named 'getAsString' in 'clang::Type'
            string typeLhs = lhs->getType()->getAsString();
                             ~~~~~~~~~~~~~~  ^

Apparently Expr::getType() returns a clang::Type, not a clang::QualType as expected.

It's weird, in the documentation it days that Expr::getType() returns a clang::QualType. Perhaps it is because the latest version of the documentation is Clang 9.0.0, but I'm using Clang 6.0.1. Maybe they changed it.

If I have a clang::Expr, whose underlying type is int or something, how can I get the int as a string, std::string("int");?


Solution

  • getAsString does provide a functionality that you're looking for.

    The problem with your code is that Expr::getType does return clang::QualType not clang::QualType *. It has an overloaded operators * and -> that return clang::Type & and that's why you get this compiler error.

    Long story short: change it to lhs->getType().getAsString()