diff --git a/clang/lib/Basic/SourceManager.cpp b/clang/lib/Basic/SourceManager.cpp index b91671ad17b1..0c22de7bddb1 100644 --- a/clang/lib/Basic/SourceManager.cpp +++ b/clang/lib/Basic/SourceManager.cpp @@ -980,20 +980,6 @@ SourceLocation SourceManager::getLocation(const FileEntry *SourceFile, if (Content->SourceLineCache == 0) ComputeLineNumbers(Content, ContentCacheAlloc); - if (Line > Content->NumLines) - return SourceLocation(); - - unsigned FilePos = Content->SourceLineCache[Line - 1]; - const char *Buf = Content->getBuffer()->getBufferStart() + FilePos; - unsigned BufLength = Content->getBuffer()->getBufferEnd() - Buf; - unsigned i = 0; - - // Check that the given column is valid. - while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r') - ++i; - if (i < Col-1) - return SourceLocation(); - // Find the first file ID that corresponds to the given file. FileID FirstFID; @@ -1020,6 +1006,24 @@ SourceLocation SourceManager::getLocation(const FileEntry *SourceFile, if (FirstFID.isInvalid()) return SourceLocation(); + if (Line > Content->NumLines) { + unsigned Size = Content->getBuffer()->getBufferSize(); + if (Size > 0) + --Size; + return getLocForStartOfFile(FirstFID).getFileLocWithOffset(Size); + } + + unsigned FilePos = Content->SourceLineCache[Line - 1]; + const char *Buf = Content->getBuffer()->getBufferStart() + FilePos; + unsigned BufLength = Content->getBuffer()->getBufferEnd() - Buf; + unsigned i = 0; + + // Check that the given column is valid. + while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r') + ++i; + if (i < Col-1) + return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + i); + return getLocForStartOfFile(FirstFID).getFileLocWithOffset(FilePos + Col - 1); } diff --git a/clang/test/Index/annotate-tokens.c b/clang/test/Index/annotate-tokens.c index ef0069c8879a..7fbf9cc4fb6e 100644 --- a/clang/test/Index/annotate-tokens.c +++ b/clang/test/Index/annotate-tokens.c @@ -61,4 +61,5 @@ void f(void *ptr) { // CHECK: Literal: ""Hello"" [9:24 - 9:31] // CHECK: Punctuation: ";" [9:31 - 9:32] // CHECK: Punctuation: "}" [10:1 - 10:2] - +// RUN: c-index-test -test-annotate-tokens=%s:4:1:165:32 %s | FileCheck %s +// RUN: c-index-test -test-annotate-tokens=%s:4:1:165:38 %s | FileCheck %s