blob: ddfaec888e2de6f8afbd19d674990a476a0acbb3 [file] [log] [blame]
Sam McCallb536a2a2017-12-19 12:23:48 +00001//===--- SourceCode.h - Manipulating source code as strings -----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9#include "SourceCode.h"
10
Marc-Andre Laperle63a10982018-02-21 02:39:08 +000011#include "clang/Basic/SourceManager.h"
Simon Marchi766338a2018-03-21 14:36:46 +000012#include "llvm/Support/Errc.h"
13#include "llvm/Support/Error.h"
Marc-Andre Laperle63a10982018-02-21 02:39:08 +000014
Sam McCallb536a2a2017-12-19 12:23:48 +000015namespace clang {
16namespace clangd {
17using namespace llvm;
18
Sam McCalla4962cc2018-04-27 11:59:28 +000019// Here be dragons. LSP positions use columns measured in *UTF-16 code units*!
20// Clangd uses UTF-8 and byte-offsets internally, so conversion is nontrivial.
21
22// Iterates over unicode codepoints in the (UTF-8) string. For each,
23// invokes CB(UTF-8 length, UTF-16 length), and breaks if it returns true.
24// Returns true if CB returned true, false if we hit the end of string.
25template <typename Callback>
26static bool iterateCodepoints(StringRef U8, const Callback &CB) {
27 for (size_t I = 0; I < U8.size();) {
28 unsigned char C = static_cast<unsigned char>(U8[I]);
29 if (LLVM_LIKELY(!(C & 0x80))) { // ASCII character.
30 if (CB(1, 1))
31 return true;
32 ++I;
33 continue;
34 }
35 // This convenient property of UTF-8 holds for all non-ASCII characters.
36 size_t UTF8Length = countLeadingOnes(C);
37 // 0xxx is ASCII, handled above. 10xxx is a trailing byte, invalid here.
38 // 11111xxx is not valid UTF-8 at all. Assert because it's probably our bug.
39 assert((UTF8Length >= 2 && UTF8Length <= 4) &&
40 "Invalid UTF-8, or transcoding bug?");
41 I += UTF8Length; // Skip over all trailing bytes.
42 // A codepoint takes two UTF-16 code unit if it's astral (outside BMP).
43 // Astral codepoints are encoded as 4 bytes in UTF-8 (11110xxx ...)
44 if (CB(UTF8Length, UTF8Length == 4 ? 2 : 1))
45 return true;
46 }
47 return false;
48}
49
50// Returns the offset into the string that matches \p Units UTF-16 code units.
51// Conceptually, this converts to UTF-16, truncates to CodeUnits, converts back
52// to UTF-8, and returns the length in bytes.
53static size_t measureUTF16(StringRef U8, int U16Units, bool &Valid) {
54 size_t Result = 0;
55 Valid = U16Units == 0 || iterateCodepoints(U8, [&](int U8Len, int U16Len) {
56 Result += U8Len;
57 U16Units -= U16Len;
58 return U16Units <= 0;
59 });
60 if (U16Units < 0) // Offset was into the middle of a surrogate pair.
61 Valid = false;
62 // Don't return an out-of-range index if we overran.
63 return std::min(Result, U8.size());
64}
65
66// Counts the number of UTF-16 code units needed to represent a string.
67// Like most strings in clangd, the input is UTF-8 encoded.
68static size_t utf16Len(StringRef U8) {
69 // A codepoint takes two UTF-16 code unit if it's astral (outside BMP).
70 // Astral codepoints are encoded as 4 bytes in UTF-8, starting with 11110xxx.
71 size_t Count = 0;
72 iterateCodepoints(U8, [&](int U8Len, int U16Len) {
73 Count += U16Len;
74 return false;
75 });
76 return Count;
77}
78
Simon Marchi766338a2018-03-21 14:36:46 +000079llvm::Expected<size_t> positionToOffset(StringRef Code, Position P,
80 bool AllowColumnsBeyondLineLength) {
Sam McCallb536a2a2017-12-19 12:23:48 +000081 if (P.line < 0)
Simon Marchi766338a2018-03-21 14:36:46 +000082 return llvm::make_error<llvm::StringError>(
83 llvm::formatv("Line value can't be negative ({0})", P.line),
84 llvm::errc::invalid_argument);
85 if (P.character < 0)
86 return llvm::make_error<llvm::StringError>(
87 llvm::formatv("Character value can't be negative ({0})", P.character),
88 llvm::errc::invalid_argument);
Sam McCallb536a2a2017-12-19 12:23:48 +000089 size_t StartOfLine = 0;
90 for (int I = 0; I != P.line; ++I) {
91 size_t NextNL = Code.find('\n', StartOfLine);
92 if (NextNL == StringRef::npos)
Simon Marchi766338a2018-03-21 14:36:46 +000093 return llvm::make_error<llvm::StringError>(
94 llvm::formatv("Line value is out of range ({0})", P.line),
95 llvm::errc::invalid_argument);
Sam McCallb536a2a2017-12-19 12:23:48 +000096 StartOfLine = NextNL + 1;
97 }
Simon Marchi766338a2018-03-21 14:36:46 +000098
99 size_t NextNL = Code.find('\n', StartOfLine);
100 if (NextNL == StringRef::npos)
101 NextNL = Code.size();
102
Sam McCalla4962cc2018-04-27 11:59:28 +0000103 bool Valid;
104 size_t ByteOffsetInLine = measureUTF16(
105 Code.substr(StartOfLine, NextNL - StartOfLine), P.character, Valid);
106 if (!Valid && !AllowColumnsBeyondLineLength)
Simon Marchi766338a2018-03-21 14:36:46 +0000107 return llvm::make_error<llvm::StringError>(
Sam McCalla4962cc2018-04-27 11:59:28 +0000108 llvm::formatv("UTF-16 offset {0} is invalid for line {1}", P.character,
109 P.line),
Simon Marchi766338a2018-03-21 14:36:46 +0000110 llvm::errc::invalid_argument);
Sam McCalla4962cc2018-04-27 11:59:28 +0000111 return StartOfLine + ByteOffsetInLine;
Sam McCallb536a2a2017-12-19 12:23:48 +0000112}
113
114Position offsetToPosition(StringRef Code, size_t Offset) {
115 Offset = std::min(Code.size(), Offset);
116 StringRef Before = Code.substr(0, Offset);
117 int Lines = Before.count('\n');
118 size_t PrevNL = Before.rfind('\n');
119 size_t StartOfLine = (PrevNL == StringRef::npos) ? 0 : (PrevNL + 1);
Ilya Biryukov7beea3a2018-02-14 10:52:04 +0000120 Position Pos;
121 Pos.line = Lines;
Sam McCalla4962cc2018-04-27 11:59:28 +0000122 Pos.character = utf16Len(Before.substr(StartOfLine));
Ilya Biryukov7beea3a2018-02-14 10:52:04 +0000123 return Pos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000124}
125
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000126Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc) {
Sam McCalla4962cc2018-04-27 11:59:28 +0000127 // We use the SourceManager's line tables, but its column number is in bytes.
128 FileID FID;
129 unsigned Offset;
130 std::tie(FID, Offset) = SM.getDecomposedSpellingLoc(Loc);
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000131 Position P;
Sam McCalla4962cc2018-04-27 11:59:28 +0000132 P.line = static_cast<int>(SM.getLineNumber(FID, Offset)) - 1;
133 bool Invalid = false;
134 StringRef Code = SM.getBufferData(FID, &Invalid);
135 if (!Invalid) {
136 auto ColumnInBytes = SM.getColumnNumber(FID, Offset) - 1;
137 auto LineSoFar = Code.substr(Offset - ColumnInBytes, ColumnInBytes);
138 P.character = utf16Len(LineSoFar);
139 }
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000140 return P;
141}
142
Ilya Biryukov71028b82018-03-12 15:28:22 +0000143Range halfOpenToRange(const SourceManager &SM, CharSourceRange R) {
144 // Clang is 1-based, LSP uses 0-based indexes.
145 Position Begin = sourceLocToPosition(SM, R.getBegin());
146 Position End = sourceLocToPosition(SM, R.getEnd());
147
148 return {Begin, End};
149}
150
Sam McCalla4962cc2018-04-27 11:59:28 +0000151std::pair<size_t, size_t> offsetToClangLineColumn(StringRef Code,
152 size_t Offset) {
153 Offset = std::min(Code.size(), Offset);
154 StringRef Before = Code.substr(0, Offset);
155 int Lines = Before.count('\n');
156 size_t PrevNL = Before.rfind('\n');
157 size_t StartOfLine = (PrevNL == StringRef::npos) ? 0 : (PrevNL + 1);
158 return {Lines + 1, Offset - StartOfLine + 1};
159}
160
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000161std::pair<llvm::StringRef, llvm::StringRef>
162splitQualifiedName(llvm::StringRef QName) {
163 size_t Pos = QName.rfind("::");
164 if (Pos == llvm::StringRef::npos)
165 return {StringRef(), QName};
166 return {QName.substr(0, Pos + 2), QName.substr(Pos + 2)};
167}
168
Sam McCallb536a2a2017-12-19 12:23:48 +0000169} // namespace clangd
170} // namespace clang