I am writing a transpiler which can translate the source language to C++. I am using flex, bison, and clang-AST for this purpose. I will start with an empty AST and with each semantic action in parsing I will add nodes to the clang-AST.
The problem is that I can't find a way to build the AST programmatically. Let say I want to generate an AST for the following code without RecursiveASTVisitor(because my source language is not C++)
#include <iostream>
int main()
{
std::cout << "Hello World " << std::endl;
return 0;
}
So the corresponding code which can generate the AST should look like this
#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;
}
The code mentioned above is not a working code and looking at the docs of llvm or clang is PITA can anybody help me out who has done any similar work?