I am working on an AST transformer using Clang. It is supposed to take the file name as input, perform some conversions to the code in this file, and return the converted code. It is based on a useful example from Eli Bendersky .
Here is the code:
std::string transform(std::string fileName) {
CompilerInstance compilerInstance;
compilerInstance.createDiagnostics();
auto& langOpts = compilerInstance.getLangOpts();
langOpts.CPlusPlus = true;
auto TO = std::make_shared<TargetOptions>();
TO->Triple = llvm::sys::getDefaultTargetTriple();
TargetInfo* targetInfo =
TargetInfo::CreateTargetInfo(compilerInstance.getDiagnostics(), TO);
compilerInstance.setTarget(targetInfo);
compilerInstance.createFileManager();
auto& fileManager = compilerInstance.getFileManager();
compilerInstance.createSourceManager(fileManager);
auto& sourceManager = compilerInstance.getSourceManager();
compilerInstance.createPreprocessor(TU_Module);
compilerInstance.createASTContext();
auto rewriter = clang::Rewriter(sourceManager, compilerInstance.getLangOpts());
const FileEntry* inputFile = fileManager.getFile(fileName);
sourceManager.setMainFileID(
sourceManager.createFileID(inputFile, SourceLocation(), SrcMgr::C_User));
compilerInstance.getDiagnosticClient().BeginSourceFile(
compilerInstance.getLangOpts(), &compilerInstance.getPreprocessor());
MyASTConsumer consumer(rewriter);
clang::ParseAST(
compilerInstance.getPreprocessor(),
&consumer,
compilerInstance.getASTContext());
const RewriteBuffer* buffer = rewriter.getRewriteBufferFor(sourceManager.getMainFileID());
return std::string(buffer->begin(), buffer->end());
}
Here is my input program negate.cpp:
bool negate(bool b) {
if (b) {
return false;
} else {
return true;
}
}
When I run transformin this code, I get the following error:
negate.cpp:1:1: error: unknown type name 'bool'
bool negate(bool b) {
^
This tells me that it works in C mode, not C ++ mode. To confirm, I replaced boolwith int, trueby, 1and falsewith 0:
int negate(int b) {
if (b) {
return 0;
} else {
return 1;
}
}
This worked, so my question is:
How to put Clang CompilerInstancein C ++ mode?
Update:
I tried changing the call but no luck:
auto& langOpts = compilerInstance.getLangOpts();
langOpts.CPlusPlus = true;
langOpts.CPlusPlus11 = true;
auto* compilerInvocation = new CompilerInvocation();
compilerInvocation->setLangDefaults(
langOpts,
clang::InputKind::IK_CXX,
LangStandard::lang_gnu11);