[cfe-dev] using clang - getting type for C variable declaration
David Blaikie
dblaikie at gmail.com
Fri Nov 9 08:18:57 PST 2012
On Fri, Nov 9, 2012 at 2:12 AM, Rajendra <rks at cse.iitb.ac.in> wrote:
> Hi,
>
> 1) I need to get type as string from Expr object. Any pointers?
Presumably Expr::getType():
http://clang.llvm.org/doxygen/classclang_1_1Expr.html#a3dd8850a4ad8a5b5f595dd9e9446187b
>
> 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);
The usual way we write these last two lines is:
if (const DeclRefExpr *declRefExpr = dyn_cast<DeclRefExpr(lhs))
no string comparison required
no double-check (the string check and then the check in the dyn_cast)
For more details on LLVM's casting machinery:
http://llvm.org/docs/ProgrammersManual.html#isa
>
> const ValueDecl *valueDecl = declRefExpr->getDecl();
>
> if (valueDecl)
Just a stylistic point related to my first (in case you're planning to
be a Clang/LLVM contributor): we usually collapse the variable
declaration into the condition.
> {
> 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
> _______________________________________________
> cfe-dev mailing list
> cfe-dev at cs.uiuc.edu
> http://lists.cs.uiuc.edu/mailman/listinfo/cfe-dev
More information about the cfe-dev
mailing list