[cfe-dev] add FieldDecl to CXXRecordDecl and save to source file

Manuel Klimek via cfe-dev cfe-dev at lists.llvm.org
Thu May 24 02:21:55 PDT 2018


Generally, the clang approach is to not change and save the AST, but change
the source code based on AST info.
A good high level explanation is here:
https://eli.thegreenplace.net/2014/07/29/ast-matchers-and-clang-refactoring-tools


On Thu, May 24, 2018 at 4:25 AM 罗 金才 via cfe-dev <cfe-dev at lists.llvm.org>
wrote:

> Hello Develpers,
>      I want to add a filedDec to CXXRecordDecl  and save it . my code as
> foloow , but how to save it?
> bool MyASTVisitor::VisitCXXRecordDecl(CXXRecordDecl *Declaration) {
> DeclContext *declContext = Declaration->getDeclContext();
> SourceManager &sourceManager_ = TheRewriter.getSourceMgr();
>
> clang::ASTContext& astContext = Declaration->getASTContext();
>
> SourceLocation startLoc = Declaration->getLocStart();
> const char* startBuf = sourceManager_.getCharacterData(startLoc);
> const char* classStartBuf = strchr(startBuf, '{')+1;
>
> SourceLocation insertStartLoc = Declaration->getLocStart().getLocWithOffset(std::distance(startBuf, classStartBuf));
>
> llvm::APInt apInt(32, 42);
>
> clang::IntegerLiteral* intergerLiteral = clang::IntegerLiteral::Create(astContext, apInt, astContext.IntTy, insertStartLoc);
>
>
> clang::TypeSourceInfo* typeSourceInfo = astContext.CreateTypeSourceInfo(astContext.IntTy);
>
> clang::IdentifierInfo& id = astContext.Idents.get("test_");
>
> clang::FieldDecl* fieldDecl = clang::FieldDecl::Create(astContext, Declaration, insertStartLoc, insertStartLoc, &id, astContext.IntTy, typeSourceInfo, intergerLiteral, false, clang::InClassInitStyle::ICIS_NoInit);
>
> fieldDecl->setAccess(clang::AccessSpecifier::AS_private);
>
> Declaration->addDecl(fieldDecl);
>
> return true;
> }
>
> Yours truly
>
> Robert
>
> _______________________________________________
> cfe-dev mailing list
> cfe-dev at lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20180524/b6e8df81/attachment.html>


More information about the cfe-dev mailing list