[cfe-dev] source code string from SourceRange?

Jordan Rose jordan_rose at apple.com
Wed Jun 19 17:22:09 PDT 2013


On Jun 19, 2013, at 13:06 , Eli Friedman <eli.friedman at gmail.com> wrote:

> On Wed, Jun 19, 2013 at 12:38 PM, Thompson, John <John_Thompson at playstation.sony.com> wrote:
>> Right off, a message elsewhere pointed me to an improvement:
>> 
>>  
>> 
>> std::string PreprocessorCallbacks::getSourceSnippet(SourceRange sourceRange) {
>> 
>>   SourceLocation bLoc(sourceRange.getBegin());
>> 
>>   SourceLocation eLoc(sourceRange.getEnd());
>> 
>>  
>> 
>>   // Decompose the locations into FID/Offset pairs.
>> 
>>   std::pair<FileID, unsigned> bLocInfo = PP.getSourceManager().getDecomposedLoc(bLoc);
>> 
>>   std::pair<FileID, unsigned> eLocInfo = PP.getSourceManager().getDecomposedLoc(eLoc);
>> 
>>   FileID FID = bLocInfo.first;
>> 
>>  unsigned bFileOffset = bLocInfo.second;
>> 
>>   unsigned eFileOffset = eLocInfo.second;
>> 
>>   unsigned length = eFileOffset - bFileOffset;
>> 
>>  
>> 
>>   // Get information about the buffer it points into.
>> 
>>   bool Invalid = false;
>> 
>>   const char *BufStart = PP.getSourceManager().getBufferData(FID, &Invalid).data();
>> 
>>   if (Invalid)
>> 
>>     return std::string();
>> 
>>  
>> 
>>   return StringRef(BufStart + bFileOffset, length).trim().str();
>> 
>> }
>> 
>>  
>> 
>> Anything better?
>> 
>>  
> 
> 
> You could use SourceManager::getCharacterData().
> 
> -Eli

You do have to be very caareful that your locations are from the same file -- macros can mess this up!

Jordan



More information about the cfe-dev mailing list