[cfe-dev] Repeat calls to ParseAST from the same compiler instance

Mohammed El-Afifi via cfe-dev cfe-dev at lists.llvm.org
Thu Oct 22 16:25:56 PDT 2015


Hello Gabe,
Gabe Svenson via cfe-dev <cfe-dev at ...> writes:

> 
> 
> Hello,
> 
> I'm trying to parse a file to do some minor source to source
transformations using clang's rewriter. I want to re-use the same compiler
instance within a parse function but atm I'm triggering this assertion when
I repeat call parseAST: 
> 
> Assertion failed: NumEnteredSourceFiles == 0 && "Cannot reenter the main
file!",
>  file F:\Clanggit\clang\lib\Lex\Preprocessor.cpp, line 483
> 
> 
> So I have this in my parsing function, what I want to know is how to reset
all the parts of the compiler (without deleting/releasing them) so that I
can repeatedly call ParseAST from the same compiler instance within a
function without triggering any asserts or having any other issues.
> 
> 
> 	// Set the main file handled by the source manager to the input file.
> 
> 	const FileEntry *FileIn =
m_compilerParseInstance->getFileManager().getFile(srcFilePath);
> 
> 	m_compilerParseInstance->getSourceManager().setMainFileID(
> 
> 		m_compilerParseInstance->getSourceManager().createFileID(FileIn,
SourceLocation(), SrcMgr::C_User));
> 
> 
> 	// Create an AST consumer instance which is going to get called by
> 
> 	// ParseAST.
> 
> 	MyASTConsumer TheConsumer(m_rewriter);
> 
> 
> 	// Parse the file to AST, registering our consumer as the AST consumer.
> 
> 	ParseAST(m_compilerParseInstance->getPreprocessor(), &TheConsumer,
> 
> 		m_compilerParseInstance->getASTContext());
> 
> 
> Thanks and best regards,
> Gabe
> 
> 
> _______________________________________________
> cfe-dev mailing list
> cfe-dev <at> lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev
> 


I ran into the same situation once and I can tell you what I've used then;
maybe it proves useful in your case.

I didn't have to recreate all the compiler instance setup, just part of it.
In specific, before parsing each file I had

m_compilerParseInstance->createPreprocessor();
m_compilerParseInstance->createASTContext();
m_compilerParseInstance->createSema(clang::TU_Complete, NULL);

And then after parsing the AST, I teared down those 3 components of the
compiler instance like

m_compilerParseInstance->setSema(NULL);
m_compilerParseInstance->setPreprocessor(NULL);
m_compilerParseInstance->setASTContext(NULL);

That was with clang 3.3 and 3.4; I don't know if these API functions have
changed in later versions of clang.

Hope it helps.


More information about the cfe-dev mailing list