Sam McCall | b536a2a | 2017-12-19 12:23:48 +0000 | [diff] [blame] | 1 | //===--- 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 Laperle | 1be6970 | 2018-07-05 19:35:01 +0000 | [diff] [blame] | 11 | #include "Logger.h" |
| 12 | #include "clang/AST/ASTContext.h" |
Marc-Andre Laperle | 63a1098 | 2018-02-21 02:39:08 +0000 | [diff] [blame] | 13 | #include "clang/Basic/SourceManager.h" |
Marc-Andre Laperle | 1be6970 | 2018-07-05 19:35:01 +0000 | [diff] [blame] | 14 | #include "clang/Lex/Lexer.h" |
Simon Marchi | 766338a | 2018-03-21 14:36:46 +0000 | [diff] [blame] | 15 | #include "llvm/Support/Errc.h" |
| 16 | #include "llvm/Support/Error.h" |
Marc-Andre Laperle | 1be6970 | 2018-07-05 19:35:01 +0000 | [diff] [blame] | 17 | #include "llvm/Support/Path.h" |
Marc-Andre Laperle | 63a1098 | 2018-02-21 02:39:08 +0000 | [diff] [blame] | 18 | |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame^] | 19 | using namespace llvm; |
Sam McCall | b536a2a | 2017-12-19 12:23:48 +0000 | [diff] [blame] | 20 | namespace clang { |
| 21 | namespace clangd { |
Sam McCall | b536a2a | 2017-12-19 12:23:48 +0000 | [diff] [blame] | 22 | |
Sam McCall | a4962cc | 2018-04-27 11:59:28 +0000 | [diff] [blame] | 23 | // Here be dragons. LSP positions use columns measured in *UTF-16 code units*! |
| 24 | // Clangd uses UTF-8 and byte-offsets internally, so conversion is nontrivial. |
| 25 | |
| 26 | // Iterates over unicode codepoints in the (UTF-8) string. For each, |
| 27 | // invokes CB(UTF-8 length, UTF-16 length), and breaks if it returns true. |
| 28 | // Returns true if CB returned true, false if we hit the end of string. |
| 29 | template <typename Callback> |
| 30 | static bool iterateCodepoints(StringRef U8, const Callback &CB) { |
| 31 | for (size_t I = 0; I < U8.size();) { |
| 32 | unsigned char C = static_cast<unsigned char>(U8[I]); |
| 33 | if (LLVM_LIKELY(!(C & 0x80))) { // ASCII character. |
| 34 | if (CB(1, 1)) |
| 35 | return true; |
| 36 | ++I; |
| 37 | continue; |
| 38 | } |
| 39 | // This convenient property of UTF-8 holds for all non-ASCII characters. |
| 40 | size_t UTF8Length = countLeadingOnes(C); |
| 41 | // 0xxx is ASCII, handled above. 10xxx is a trailing byte, invalid here. |
| 42 | // 11111xxx is not valid UTF-8 at all. Assert because it's probably our bug. |
| 43 | assert((UTF8Length >= 2 && UTF8Length <= 4) && |
| 44 | "Invalid UTF-8, or transcoding bug?"); |
| 45 | I += UTF8Length; // Skip over all trailing bytes. |
| 46 | // A codepoint takes two UTF-16 code unit if it's astral (outside BMP). |
| 47 | // Astral codepoints are encoded as 4 bytes in UTF-8 (11110xxx ...) |
| 48 | if (CB(UTF8Length, UTF8Length == 4 ? 2 : 1)) |
| 49 | return true; |
| 50 | } |
| 51 | return false; |
| 52 | } |
| 53 | |
| 54 | // Returns the offset into the string that matches \p Units UTF-16 code units. |
| 55 | // Conceptually, this converts to UTF-16, truncates to CodeUnits, converts back |
| 56 | // to UTF-8, and returns the length in bytes. |
| 57 | static size_t measureUTF16(StringRef U8, int U16Units, bool &Valid) { |
| 58 | size_t Result = 0; |
| 59 | Valid = U16Units == 0 || iterateCodepoints(U8, [&](int U8Len, int U16Len) { |
| 60 | Result += U8Len; |
| 61 | U16Units -= U16Len; |
| 62 | return U16Units <= 0; |
| 63 | }); |
| 64 | if (U16Units < 0) // Offset was into the middle of a surrogate pair. |
| 65 | Valid = false; |
| 66 | // Don't return an out-of-range index if we overran. |
| 67 | return std::min(Result, U8.size()); |
| 68 | } |
| 69 | |
| 70 | // Counts the number of UTF-16 code units needed to represent a string. |
| 71 | // Like most strings in clangd, the input is UTF-8 encoded. |
| 72 | static size_t utf16Len(StringRef U8) { |
| 73 | // A codepoint takes two UTF-16 code unit if it's astral (outside BMP). |
| 74 | // Astral codepoints are encoded as 4 bytes in UTF-8, starting with 11110xxx. |
| 75 | size_t Count = 0; |
| 76 | iterateCodepoints(U8, [&](int U8Len, int U16Len) { |
| 77 | Count += U16Len; |
| 78 | return false; |
| 79 | }); |
| 80 | return Count; |
| 81 | } |
| 82 | |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame^] | 83 | Expected<size_t> positionToOffset(StringRef Code, Position P, |
| 84 | bool AllowColumnsBeyondLineLength) { |
Sam McCall | b536a2a | 2017-12-19 12:23:48 +0000 | [diff] [blame] | 85 | if (P.line < 0) |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame^] | 86 | return make_error<StringError>( |
| 87 | formatv("Line value can't be negative ({0})", P.line), |
| 88 | errc::invalid_argument); |
Simon Marchi | 766338a | 2018-03-21 14:36:46 +0000 | [diff] [blame] | 89 | if (P.character < 0) |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame^] | 90 | return make_error<StringError>( |
| 91 | formatv("Character value can't be negative ({0})", P.character), |
| 92 | errc::invalid_argument); |
Sam McCall | b536a2a | 2017-12-19 12:23:48 +0000 | [diff] [blame] | 93 | size_t StartOfLine = 0; |
| 94 | for (int I = 0; I != P.line; ++I) { |
| 95 | size_t NextNL = Code.find('\n', StartOfLine); |
| 96 | if (NextNL == StringRef::npos) |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame^] | 97 | return make_error<StringError>( |
| 98 | formatv("Line value is out of range ({0})", P.line), |
| 99 | errc::invalid_argument); |
Sam McCall | b536a2a | 2017-12-19 12:23:48 +0000 | [diff] [blame] | 100 | StartOfLine = NextNL + 1; |
| 101 | } |
Simon Marchi | 766338a | 2018-03-21 14:36:46 +0000 | [diff] [blame] | 102 | |
| 103 | size_t NextNL = Code.find('\n', StartOfLine); |
| 104 | if (NextNL == StringRef::npos) |
| 105 | NextNL = Code.size(); |
| 106 | |
Sam McCall | a4962cc | 2018-04-27 11:59:28 +0000 | [diff] [blame] | 107 | bool Valid; |
| 108 | size_t ByteOffsetInLine = measureUTF16( |
| 109 | Code.substr(StartOfLine, NextNL - StartOfLine), P.character, Valid); |
| 110 | if (!Valid && !AllowColumnsBeyondLineLength) |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame^] | 111 | return make_error<StringError>( |
| 112 | formatv("UTF-16 offset {0} is invalid for line {1}", P.character, |
| 113 | P.line), |
| 114 | errc::invalid_argument); |
Sam McCall | a4962cc | 2018-04-27 11:59:28 +0000 | [diff] [blame] | 115 | return StartOfLine + ByteOffsetInLine; |
Sam McCall | b536a2a | 2017-12-19 12:23:48 +0000 | [diff] [blame] | 116 | } |
| 117 | |
| 118 | Position offsetToPosition(StringRef Code, size_t Offset) { |
| 119 | Offset = std::min(Code.size(), Offset); |
| 120 | StringRef Before = Code.substr(0, Offset); |
| 121 | int Lines = Before.count('\n'); |
| 122 | size_t PrevNL = Before.rfind('\n'); |
| 123 | size_t StartOfLine = (PrevNL == StringRef::npos) ? 0 : (PrevNL + 1); |
Ilya Biryukov | 7beea3a | 2018-02-14 10:52:04 +0000 | [diff] [blame] | 124 | Position Pos; |
| 125 | Pos.line = Lines; |
Sam McCall | a4962cc | 2018-04-27 11:59:28 +0000 | [diff] [blame] | 126 | Pos.character = utf16Len(Before.substr(StartOfLine)); |
Ilya Biryukov | 7beea3a | 2018-02-14 10:52:04 +0000 | [diff] [blame] | 127 | return Pos; |
Sam McCall | b536a2a | 2017-12-19 12:23:48 +0000 | [diff] [blame] | 128 | } |
| 129 | |
Marc-Andre Laperle | 63a1098 | 2018-02-21 02:39:08 +0000 | [diff] [blame] | 130 | Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc) { |
Sam McCall | a4962cc | 2018-04-27 11:59:28 +0000 | [diff] [blame] | 131 | // We use the SourceManager's line tables, but its column number is in bytes. |
| 132 | FileID FID; |
| 133 | unsigned Offset; |
| 134 | std::tie(FID, Offset) = SM.getDecomposedSpellingLoc(Loc); |
Marc-Andre Laperle | 63a1098 | 2018-02-21 02:39:08 +0000 | [diff] [blame] | 135 | Position P; |
Sam McCall | a4962cc | 2018-04-27 11:59:28 +0000 | [diff] [blame] | 136 | P.line = static_cast<int>(SM.getLineNumber(FID, Offset)) - 1; |
| 137 | bool Invalid = false; |
| 138 | StringRef Code = SM.getBufferData(FID, &Invalid); |
| 139 | if (!Invalid) { |
| 140 | auto ColumnInBytes = SM.getColumnNumber(FID, Offset) - 1; |
| 141 | auto LineSoFar = Code.substr(Offset - ColumnInBytes, ColumnInBytes); |
| 142 | P.character = utf16Len(LineSoFar); |
| 143 | } |
Marc-Andre Laperle | 63a1098 | 2018-02-21 02:39:08 +0000 | [diff] [blame] | 144 | return P; |
| 145 | } |
| 146 | |
Ilya Biryukov | 71028b8 | 2018-03-12 15:28:22 +0000 | [diff] [blame] | 147 | Range halfOpenToRange(const SourceManager &SM, CharSourceRange R) { |
| 148 | // Clang is 1-based, LSP uses 0-based indexes. |
| 149 | Position Begin = sourceLocToPosition(SM, R.getBegin()); |
| 150 | Position End = sourceLocToPosition(SM, R.getEnd()); |
| 151 | |
| 152 | return {Begin, End}; |
| 153 | } |
| 154 | |
Sam McCall | a4962cc | 2018-04-27 11:59:28 +0000 | [diff] [blame] | 155 | std::pair<size_t, size_t> offsetToClangLineColumn(StringRef Code, |
| 156 | size_t Offset) { |
| 157 | Offset = std::min(Code.size(), Offset); |
| 158 | StringRef Before = Code.substr(0, Offset); |
| 159 | int Lines = Before.count('\n'); |
| 160 | size_t PrevNL = Before.rfind('\n'); |
| 161 | size_t StartOfLine = (PrevNL == StringRef::npos) ? 0 : (PrevNL + 1); |
| 162 | return {Lines + 1, Offset - StartOfLine + 1}; |
| 163 | } |
| 164 | |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame^] | 165 | std::pair<StringRef, StringRef> splitQualifiedName(StringRef QName) { |
Marc-Andre Laperle | b387b6e | 2018-04-23 20:00:52 +0000 | [diff] [blame] | 166 | size_t Pos = QName.rfind("::"); |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame^] | 167 | if (Pos == StringRef::npos) |
Marc-Andre Laperle | b387b6e | 2018-04-23 20:00:52 +0000 | [diff] [blame] | 168 | return {StringRef(), QName}; |
| 169 | return {QName.substr(0, Pos + 2), QName.substr(Pos + 2)}; |
| 170 | } |
| 171 | |
Eric Liu | 9133ecd | 2018-05-11 12:12:08 +0000 | [diff] [blame] | 172 | TextEdit replacementToEdit(StringRef Code, const tooling::Replacement &R) { |
| 173 | Range ReplacementRange = { |
| 174 | offsetToPosition(Code, R.getOffset()), |
| 175 | offsetToPosition(Code, R.getOffset() + R.getLength())}; |
| 176 | return {ReplacementRange, R.getReplacementText()}; |
| 177 | } |
| 178 | |
| 179 | std::vector<TextEdit> replacementsToEdits(StringRef Code, |
| 180 | const tooling::Replacements &Repls) { |
| 181 | std::vector<TextEdit> Edits; |
| 182 | for (const auto &R : Repls) |
| 183 | Edits.push_back(replacementToEdit(Code, R)); |
| 184 | return Edits; |
| 185 | } |
| 186 | |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame^] | 187 | Optional<std::string> getRealPath(const FileEntry *F, |
| 188 | const SourceManager &SourceMgr) { |
Simon Marchi | 25f1f73 | 2018-08-10 22:27:53 +0000 | [diff] [blame] | 189 | // Ideally, we get the real path from the FileEntry object. |
| 190 | SmallString<128> FilePath = F->tryGetRealPathName(); |
| 191 | if (!FilePath.empty()) { |
| 192 | return FilePath.str().str(); |
| 193 | } |
| 194 | |
| 195 | // Otherwise, we try to compute ourselves. |
| 196 | vlog("FileEntry for {0} did not contain the real path.", F->getName()); |
| 197 | |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame^] | 198 | SmallString<128> Path = F->getName(); |
Simon Marchi | 25f1f73 | 2018-08-10 22:27:53 +0000 | [diff] [blame] | 199 | |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame^] | 200 | if (!sys::path::is_absolute(Path)) { |
Simon Marchi | 25f1f73 | 2018-08-10 22:27:53 +0000 | [diff] [blame] | 201 | if (!SourceMgr.getFileManager().makeAbsolutePath(Path)) { |
| 202 | log("Could not turn relative path to absolute: {0}", Path); |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame^] | 203 | return None; |
Marc-Andre Laperle | 1be6970 | 2018-07-05 19:35:01 +0000 | [diff] [blame] | 204 | } |
| 205 | } |
Simon Marchi | 25f1f73 | 2018-08-10 22:27:53 +0000 | [diff] [blame] | 206 | |
Sam McCall | c008af6 | 2018-10-20 15:30:37 +0000 | [diff] [blame^] | 207 | SmallString<128> RealPath; |
Simon Marchi | 25f1f73 | 2018-08-10 22:27:53 +0000 | [diff] [blame] | 208 | if (SourceMgr.getFileManager().getVirtualFileSystem()->getRealPath( |
| 209 | Path, RealPath)) { |
| 210 | log("Could not compute real path: {0}", Path); |
| 211 | return Path.str().str(); |
| 212 | } |
| 213 | |
| 214 | return RealPath.str().str(); |
Marc-Andre Laperle | 1be6970 | 2018-07-05 19:35:01 +0000 | [diff] [blame] | 215 | } |
| 216 | |
Kadir Cetinkaya | 2f84d91 | 2018-08-08 08:59:29 +0000 | [diff] [blame] | 217 | TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M, |
| 218 | const LangOptions &L) { |
| 219 | TextEdit Result; |
| 220 | Result.range = |
| 221 | halfOpenToRange(M, Lexer::makeFileCharRange(FixIt.RemoveRange, M, L)); |
| 222 | Result.newText = FixIt.CodeToInsert; |
| 223 | return Result; |
| 224 | } |
| 225 | |
Kadir Cetinkaya | a9c9d00 | 2018-08-13 08:23:01 +0000 | [diff] [blame] | 226 | bool IsRangeConsecutive(const Range &Left, const Range &Right) { |
| 227 | return Left.end.line == Right.start.line && |
| 228 | Left.end.character == Right.start.character; |
| 229 | } |
| 230 | |
Sam McCall | b536a2a | 2017-12-19 12:23:48 +0000 | [diff] [blame] | 231 | } // namespace clangd |
| 232 | } // namespace clang |