[cfe-dev] using clang - getting type for C variable declaration
Rajendra
rks at cse.iitb.ac.in
Fri Nov 9 02:12:19 PST 2012
Hi,
1) I need to get type as string from Expr object. Any pointers?
Expr* lhs = E->getLHS();
if (strcmp(lhs->getStmtClassName(), "DeclRefExpr") == 0)
{
// get name and type for Expr *lhs from DeclRefExpr
const DeclRefExpr *declRefExpr = dyn_cast<DeclRefExpr>(lhs);
const ValueDecl *valueDecl = declRefExpr->getDecl();
if (valueDecl)
{
std::cerr << "\tLHS identifier = " <<
valueDecl->getNameAsString() << "\n"; // this gives x
QualType declQT = valueDecl->getType();
std::cerr << "\tqual type: ";
declQT.dump(); // this prints : int identifier
// now call QualType.getAsString(PrintingPolicy &Policy)
// ---> how to get compiler instance and AST context? <---- //
clang::ASTContext &context =
compilerInstance_ptr->getASTContext();
std::cerr << "\ttype: " <<
declQT.getAsString(context.getPrintingPolicy()) << "\n";
}
}
2) Here is how I got things right for Decl :) this will be helpful for
others as well.
clang::DeclGroupRef::iterator it;
for (it = declGroupRef.begin(); it != declGroupRef.end(); it++)
{
clang::Decl* decl = *it;
const NamedDecl *namedDecl = dyn_cast<NamedDecl>(decl);
if (namedDecl)
{
std::cerr << "\tidentifier name = "
<< namedDecl->getNameAsString() << "\n";
}
const ValueDecl *valueDecl = dyn_cast<ValueDecl>(decl);
if (valueDecl)
{
QualType declQT = valueDecl->getType();
// now call QualType.getAsString(PrintingPolicy &Policy)
clang::ASTContext &context = decl->getASTContext();
std::cerr << "\ttype = " <<
declQT.getAsString(context.getPrintingPolicy()) << "\n";
}
}
Rajendra
More information about the cfe-dev
mailing list