[cfe-dev] source code string from SourceRange?

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


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?


From: Thompson, John
Sent: Wednesday, June 19, 2013 12:32 PM
To: cfe-dev at cs.uiuc.edu
Subject: source code string from SourceRange?

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/a64ebb85/attachment.html>


More information about the cfe-dev mailing list