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

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