[cfe-dev] source code string from SourceRange?

Eli Friedman eli.friedman at gmail.com
Wed Jun 19 13:06:33 PDT 2013


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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20130619/5bd032a0/attachment.html>


More information about the cfe-dev mailing list