Search code examples
c++clanglibtooling

How to expand a complex typedef to its basic built-in form using clang?


I want to be able to get the original type from the complex typedef. I'm using clang version 7.1.0

Look at the code below

typedef unsigned int uint32;
typedef uint32 * p_uint32;

p_uint32 p_uint_var;

I can extract type of p_uint_var using VisitVarDecl like so

virtual bool VisitVarDecl(VarDecl *var)
{
    if(var->hasGlobalStorage())
    {
        llvm::outs() << var->getType().getAsString() << " " << var->getName() << "\n";
    }

    return true;
}

the output i get is this

p_uint32 p_uint_var

what I would like to recieve is this

unsigned int * p_uint_var

How can I achieve this?


Solution

  • The thing that you are looking for is canonical type. In this question, you can read about canonical type in Clang and different situations involving it.

    Transforming it into the actual code we get this:

    bool VisitVarDecl(VarDecl *Var) {
      llvm::outs() << Var->getType().getCanonicalType().getAsString() << " "
                   << Var->getName() << "\n";
      return true;
    }
    

    This code produces the following output for your code snippet:

    unsigned int * p_uint_var
    

    NOTE: don't make visit functions virtual. All Clang visitor classes are CRTP.

    I hope this information is useful. Happy hacking with Clang!