我正在编写一个可以将源语言翻译成C ++的编译器。我为此使用flex,bison和clang-AST。我将从一个空的AST开始,并在解析每个语义动作时,将节点添加到clang-AST中。
问题是我找不到以编程方式构建AST的方法。假设我想为下面的代码生成一个AST而没有RecursiveASTVisitor(因为我的源语言不是C ++)
#include <iostream>
int main()
{
std::cout << "Hello World " << std::endl;
return 0;
}
因此可以生成AST的相应代码应如下所示
#include "clang/AST/ASTContext.h"
int main(int argc, const char **argv)
{
//Create an empty context
clang::ASTContext *context = new clang::ASTContext(NULL, NULL, NULL, NULL, NULL);
//Declare a main function
clang::FunctionDecl *FD = clang::FunctionDecl::Create(Context, "main");
//Declare params
std::vector<clang::ParmVarDecl*> NewParamInfo;
NewParamInfo.push_back(clang::ParmVarDecl::Create(Context, FD, "argc"));
NewParamInfo.push_back(clang::ParmVarDecl::Create(Context, FD, "argv"));
//set params to function
FD->setParams(ArrayRef<clang::ParmVarDecl*>(NewParamInfo));
//Declare a compund stament
clang::CompoundStmt *CS = new (Context) clang::CompoundStmt(clang::SourceLocation());
//Declare a Statement to print
clang::Stmt *S = new (Context) clang::ReturnStmt("std::cout << \"Hello World \" << std::endl;");
//Add print statement to compund statement
CS->setStmts(Context, S, 1);
//Add compund statement to body of function
FD->setBody(CS);
return 0;
}
上面提到的代码不是有效的代码,查看llvm或clang的文档是否是PITA,有人可以帮助我完成谁的类似工作吗?
答案 0 :(得分:0)
也有许多评论者嘲笑将 clang 的 AST 用作数据结构。他们会避免使用 clang 的 AST 来“发出源代码”,但要发出非平凡的源代码,必须重新发明自己的 AST。为什么要重新发明 C++-AST 轮子?只需通过重构 API 构建 clang 的 AST,而不是从头开始设计您自己的 AST。然后作为您对预期转译的所有“重构”完成后的最后一步,通过访问者遍历从 clang AST 读取生成的 C++ 源代码。