mikebloch mikebloch - 4 months ago 17
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?


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),