获取源代码背后clang的AST [英] Getting the source behind clang's AST

查看:621
本文介绍了获取源代码背后clang的AST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在clang中给定一个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";

但是唉,它没有打印整个typedef声明,只有大约一半!打印 Expr 时会出现同样的现象。

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

如何打印并查看构成声明的整个原始字符串?

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

推荐答案

使用 Lexer 模块:

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),
        sm->getCharacterData(e)-sm->getCharacterData(b));
}

这篇关于获取源代码背后clang的AST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆