[cfe-dev] Getting preprocessed text between two source location.

Simone Pellegrini spellegrini at dps.uibk.ac.at
Fri Feb 20 08:26:48 PST 2009


Here it is the code that can help u:

ASTContext* ctx = ...;

const LangOptions &LangOpts = pp.getLangOptions();
TokenRewriter Rewriter(ctx->getSourceManager().getMainFileID(), 
ctx->getSourceManager(), LangOpts);

// Print out the output.
for (TokenRewriter::token_iterator I = Rewriter.token_begin(), E = 
Rewriter.token_end(); I != E; ++I)
    out << pp.getSpelling(*I);

this piece of code return the text in all the source file, but you can 
easily check if the location of the current token is inside or outside 
the region you are interested in.

just rewrite in this way:
for (TokenRewriter::token_iterator I = Rewriter.token_begin(), E = 
Rewriter.token_end(); I != E; ++I)
    
if(ctx->getSourceManager().getInstantiationLineNumber((*I).getLocation()) 
 > location ) ... or whatever you need to check
        out << pp.getSpelling(*I);

and it should work! It works for me! But beware that the TokenRewriter 
prints out the source file in the original version, if you modify the 
AST... the TokenRewriter will continue to show the original tree. In 
order to print out the modified AST you have to use the printPretty() 
method in the Stmt class.

cheers, Simone

Paolo Bolzoni wrote:
> On Mon, 16 Feb 2009 21:51:30 +0100
> Paolo Bolzoni <bolzoni at cs.unipr.it> wrote:
>   
>> dear cfe list,
>>
>> I need to get the preprocessed text between two source locations in order to
>> Lex again and check for code proprieties (e.g., in a const int declaration
>> see if it was actually `int const' or `const int')
>>
>> Thanks,
>> pb
>>     
>
> I am really stuck with this issue, there is really no way to get the
> unadorned text between two source locations?
>
> pb
> _______________________________________________
> cfe-dev mailing list
> cfe-dev at cs.uiuc.edu
> http://lists.cs.uiuc.edu/mailman/listinfo/cfe-dev
>   



More information about the cfe-dev mailing list