Hello.<br>I am traying to get AST of specified file and iterate trough it. Here is my code:<br><br><div style="margin-left:40px"><br>class MyDiagnosticConsumer: public clang::DiagnosticConsumer<br>{<br>public:<br> clang::DiagnosticConsumer* clone(clang::DiagnosticsEngine &Diags) const<br>
{<br> return new MyDiagnosticConsumer;<br> }<br>};<br><br>class MyModuleLoader: public clang::ModuleLoader<br>{<br>public:<br> clang::Module* loadModule(clang::SourceLocation importLoc, clang::ModuleIdPath path, clang::Module::NameVisibilityKind visibility, bool isInclusionDirective)<br>
{<br> //just do some parsing, forget about modules:<br> return NULL;<br> }<br>};<br><br>class MyASTConsumer: public clang::SemaConsumer<br>{<br>public:<br><br> bool HandleTopLevelDecl(clang::DeclGroupRef D)<br>
{<br> //never get here...<br> <br> return true;<br> }<br><br> void HandleTranslationUnit(clang::ASTContext &Ctx)<br> {<br> //not here either...<br> }<br>};<br><br><br>int main()<br>
{<br> clang::IntrusiveRefCntPtr<clang::DiagnosticIDs> diags;<br> MyDiagnosticConsumer dc;<br> clang::DiagnosticsEngine de(diags, &dc, false);<br> clang::Diagnostic d(&de);<br><br> clang::TargetOptions to;<br>
to.Triple = llvm::Triple::getArchTypeName(llvm::Triple::x86);<br> clang::TargetInfo* ti = clang::TargetInfo::CreateTargetInfo(de, to);<br><br> clang::FileSystemOptions fso;<br> clang::FileManager fm(fso);<br>
clang::SourceManager sm(de, fm);<br><br> clang::LangOptions lo;<br> clang::HeaderSearch hs(fm, de, lo, ti);<br><br> MyModuleLoader ml;<br><br> clang::Preprocessor p(de, lo, ti, sm, hs, ml);<br><br> const clang::FileEntry* file = fm.getFile("test.cpp");<br>
sm.createMainFileID(file);<br> p.EnterMainSourceFile();<br><br> clang::IdentifierTable it(lo);<br> clang::SelectorTable st;<br> clang::Builtin::Context b_c;<br> clang::ASTContext astContext(lo, sm, ti, it, st, b_c, 0);<br>
MyASTConsumer astConsumer;<br> clang::Sema s(p, astContext, astConsumer);<br> clang::Parser parser(p, s, false);<br><br> parser.Initialize();<br> clang::Parser::DeclGroupPtrTy result;<br> while(!parser.ParseTopLevelDecl(result))<br>
{<br> if ( result.get().isSingleDecl() )<br> {<br> clang::Decl* decl = result.get().getSingleDecl();<br><br> clang::FunctionDecl* fd = clang::dyn_cast_or_null<clang::FunctionDecl>(decl);<br>
<br> if ( fd->hasBody() )<br> {<br> clang::Stmt* s = fd->getBody();<br> //don't know what to do with obtained statement...<br> }<br> }<br> else if ( result.get().isDeclGroup() )<br>
{<br> clang::DeclGroup& declGroup = result.get().getDeclGroup();<br> }<br> }<br><br> getchar();<br><br> return 0;<br>}<br><br><br></div>test.cpp is:<br><div style="margin-left:40px">
int main()<br>{<br> return 5;<br>}<br><br></div>Am I on a wrong way? How is it need to parse files and iterate trough resulting AST?<br>Thank you.<br>