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