[cfe-dev] Obtaining C++ AST.
Slav
slavmfm at gmail.com
Wed May 16 13:38:26 PDT 2012
Hello.
I am traying to get AST of specified file and iterate trough it. Here is my
code:
class MyDiagnosticConsumer: public clang::DiagnosticConsumer
{
public:
clang::DiagnosticConsumer* clone(clang::DiagnosticsEngine &Diags) const
{
return new MyDiagnosticConsumer;
}
};
class MyModuleLoader: public clang::ModuleLoader
{
public:
clang::Module* loadModule(clang::SourceLocation importLoc,
clang::ModuleIdPath path, clang::Module::NameVisibilityKind visibility,
bool isInclusionDirective)
{
//just do some parsing, forget about modules:
return NULL;
}
};
class MyASTConsumer: public clang::SemaConsumer
{
public:
bool HandleTopLevelDecl(clang::DeclGroupRef D)
{
//never get here...
return true;
}
void HandleTranslationUnit(clang::ASTContext &Ctx)
{
//not here either...
}
};
int main()
{
clang::IntrusiveRefCntPtr<clang::DiagnosticIDs> diags;
MyDiagnosticConsumer dc;
clang::DiagnosticsEngine de(diags, &dc, false);
clang::Diagnostic d(&de);
clang::TargetOptions to;
to.Triple = llvm::Triple::getArchTypeName(llvm::Triple::x86);
clang::TargetInfo* ti = clang::TargetInfo::CreateTargetInfo(de, to);
clang::FileSystemOptions fso;
clang::FileManager fm(fso);
clang::SourceManager sm(de, fm);
clang::LangOptions lo;
clang::HeaderSearch hs(fm, de, lo, ti);
MyModuleLoader ml;
clang::Preprocessor p(de, lo, ti, sm, hs, ml);
const clang::FileEntry* file = fm.getFile("test.cpp");
sm.createMainFileID(file);
p.EnterMainSourceFile();
clang::IdentifierTable it(lo);
clang::SelectorTable st;
clang::Builtin::Context b_c;
clang::ASTContext astContext(lo, sm, ti, it, st, b_c, 0);
MyASTConsumer astConsumer;
clang::Sema s(p, astContext, astConsumer);
clang::Parser parser(p, s, false);
parser.Initialize();
clang::Parser::DeclGroupPtrTy result;
while(!parser.ParseTopLevelDecl(result))
{
if ( result.get().isSingleDecl() )
{
clang::Decl* decl = result.get().getSingleDecl();
clang::FunctionDecl* fd =
clang::dyn_cast_or_null<clang::FunctionDecl>(decl);
if ( fd->hasBody() )
{
clang::Stmt* s = fd->getBody();
//don't know what to do with obtained statement...
}
}
else if ( result.get().isDeclGroup() )
{
clang::DeclGroup& declGroup = result.get().getDeclGroup();
}
}
getchar();
return 0;
}
test.cpp is:
int main()
{
return 5;
}
Am I on a wrong way? How is it need to parse files and iterate trough
resulting AST?
Thank you.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20120516/b0cccbe1/attachment.html>
More information about the cfe-dev
mailing list