[cfe-dev] source code string from SourceRange?

Thompson, John John_Thompson at playstation.sony.com
Wed Jun 19 12:31:58 PDT 2013


Is there a function somewhere for getting a source string from a SourceRange using a SourceManager?

I couldn't find one so I wrote:

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();

  // Rewind from the current position to the start of the line.
  const char *bPtr = BufStart + bFileOffset;

  // Trim snippet.
  while ((*bPtr <= ' ') && (length != 0)) {
    bPtr++;
    length--;
  }

  while ((length != 0) && (bPtr[length - 1] <= ' '))
    length--;

  return std::string(bPtr, length);
}

Is there something better?

Thanks.

-John

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20130619/358b233d/attachment.html>


More information about the cfe-dev mailing list