有没有一种优雅的方式来遍历 Clang AST 语句
Is there an elegant way to traverse Clang AST Statements?
我正在尝试遍历所有函数定义并从中提取信息。我必须遍历函数体中的所有语句,并根据类型执行特定函数。
目前我有一个丑陋的if-else块。有没有更优雅的方法可以做到这一点?
void FunctionMatcher::processStatement(const clang::Stmt *statement) {
string type = statement->getStmtClassName();
if (type == "ReturnStmt") {
auto rs = dyn_cast<const ReturnStmt *>(statement);
processReturnStmt(rs);
} else if (type == "WhileStmt") {
auto ws = dyn_cast<WhileStmt>(statement);
processWhileStmt(ws);
} else if (type == "ForStmt") {
auto fs = dyn_cast<const ForStmt *>(statement);
processForStmt(fs);
} else if (type == "IfStmt") {
auto is = dyn_cast<const IfStmt *>(statement);
processIfStmt(is);
} else if (type == "SwitchStmt") {
auto ss = dyn_cast<const SwitchStmt *>(statement);
processSwitchStmt(ss);
} else if (type == "CompoundStmt") {
auto cs = dyn_cast<const CompoundStmt *>(statement);
for (auto child : cs->children())
processStatement(child);
} else {
// ...
}
通过浏览 clang::TextNodeDumper 的代码,我找到了一个解决方案。显然,Clang有自己的访客来发表声明,声明等...简单的例子:
class StatementVisitor : public ConstStmtVisitor<StatementVisitor> {
public:
StatementVisitor();
void Visit(const Stmt *Node) {
ConstStmtVisitor<StatementVisitor>::Visit(Node);
}
void VisitIfStmt(const IfStmt *Node) {
llvm::outs() << " An if statement yay!n";
}
void VisitWhileStmt(const WhileStmt *Node) {
llvm::outs() << " A While statement yay!n";
}
};
您可以使用RecursiveASTVisitor
它递归遍历给定代码中的所有语句
class MyASTVisitor : public RecursiveASTVisitor<MyASTVisitor>
{
public:
bool VisitFunctionDecl(FunctionDecl* f)
{
...
}
bool VisitIfStmt(IfStmt* IF)
{
...
}
bool VisitForStmt(ForStmt* FS)
{
...
}
bool VisitWhileStmt(WhileStmt* WS)
{
...
}
}
相关文章:
- 有什么方法可以遍历结构吗
- 在循环中按顺序遍历成员变量
- 遍历模板参数
- 在遍历处理程序的向量时注册和注销处理程序
- C++RapidXml-使用first_node()遍历以修改XML文件中节点的值
- 遍历并行数组以确定C++中的最大数字
- 遍历顺序由 std::文件系统directory_iterator给出
- 遍历链表时的无限循环
- 遍历unordered_map向量
- 是否有任何优雅的方式来遍历元素位置可以更改的列表?
- 数组数据以错误的方式遍历 Python/Matlab
- 有没有一种优雅的方式来遍历 Clang AST 语句
- 图论 - 从顶点 A 开始,遍历两个方向的所有路径,最后以最短的方式再次到达 A
- C++,如何创建和绘制二叉树,然后按预购方式遍历它
- 如果我们使用链表数组来实现哈希表,则可以以不需要遍历的方式实现"add"。这是真的还是假的?
- 逐行循环遍历char数组的最佳方式
- 以C++方式遍历.bmp的像素
- 以旧方式C++遍历对象指针数组(没有基于范围的 for)
- 有没有办法以编程方式遍历头文件
- 如何遍历boost::fusion关联结构并以通用方式访问键