[cfe-dev] source code string from SourceRange?

Guillaume Papin guillaume.papin at epitech.eu
Tue Jun 25 02:21:05 PDT 2013


I also wrote my own but I realize today that a function already exists: 
Lexer::getSourceText()

> llvm::StringRef s = 
Lexer::getSourceText(CharSourceRange::getTokenRange(Range),
>                                          SM, LangOptions);


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
  


-- 
Guillaume Papin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20130625/0e73de53/attachment.html>


More information about the cfe-dev mailing list