Get AST for C fragment using Clang?

I am creating a clang plugin and I am trying to create an AST for a C snippet at some point in the plugin. Something like:

std::string c_code = "...";
getAST(c_code);

      

Can anyone point me to how to do this?

+3


source to share


2 answers


Maybe there are several ways to achieve this, but finally I got the following snippet and it looks simple enough to me:

//arguments to the compiler
std::unique_ptr <std::vector<const char*>> args(new std::vector<const char*>());
args->push_back("my_file.c");

//do the magic
ASTUnit *au = ASTUnit::LoadFromCommandLine(
  &(*args)[0],
  &(*args)[0] + args->size(),
  IntrusiveRefCntPtr<DiagnosticsEngine>(
    CompilerInstance::createDiagnostics(new DiagnosticOptions)),
  StringRef()
);

//get the translation unit node
Declr *d = au->getASTContext().getTranslationUnitDecl();

      



Simple alternatives or suggestions for improving this are welcome.

+1


source


I don't have any ready-made copy-paste code, but the idea I used earlier is as follows:



Note that clang_parseTranslationUnit takes unsaved_files

one of the arguments. So the idea would be to provide the command line g++ main.cpp

and then provide the unsaved file with the name main.cpp

and content from your line.

-1


source







All Articles