mikebloch mikebloch - 1 year ago 89
C++ Question

Getting the source behind clang's AST

Given an AST object in clang, how can I get the code behind it? I tried editing the code in the tutorial, and added:

clang::SourceLocation _b = d->getLocStart(), _e = d->getLocEnd();
char *b = sourceManager->getCharacterData(_b),
e = sourceManager->getCharacterData(_E);
llvm:errs() << std::string(b, e-b) << "\n";

but alas, it didn't print the whole typedef declaration, only about half of it! The same phenomena happened when printing

How can I print and see the whole original string constituting the declaration?

Answer Source

Use the Lexer module:

clang::SourceManager *sm;
clang::LangOptions lopt;

std::string decl2str(clang::Decl *d) {
    clang::SourceLocation b(d->getLocStart()), _e(d->getLocEnd());
    clang::SourceLocation e(clang::Lexer::getLocForEndOfToken(_e, 0, *sm, lopt));
    return std::string(sm->getCharacterData(b),
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download