blob: ede643537affa1dfcb2f3e3d7eec6a37e203dddd [file] [log] [blame]
Sam McCallb536a2a2017-12-19 12:23:48 +00001//===--- SourceCode.h - Manipulating source code as strings -----*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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 McCallb536a2a2017-12-19 12:23:48 +00006//
7//===----------------------------------------------------------------------===//
8#include "SourceCode.h"
9
Marc-Andre Laperle1be69702018-07-05 19:35:01 +000010#include "Logger.h"
11#include "clang/AST/ASTContext.h"
Marc-Andre Laperle63a10982018-02-21 02:39:08 +000012#include "clang/Basic/SourceManager.h"
Marc-Andre Laperle1be69702018-07-05 19:35:01 +000013#include "clang/Lex/Lexer.h"
Simon Marchi766338a2018-03-21 14:36:46 +000014#include "llvm/Support/Errc.h"
15#include "llvm/Support/Error.h"
Marc-Andre Laperle1be69702018-07-05 19:35:01 +000016#include "llvm/Support/Path.h"
Marc-Andre Laperle63a10982018-02-21 02:39:08 +000017
Sam McCallb536a2a2017-12-19 12:23:48 +000018namespace clang {
19namespace clangd {
Sam McCallb536a2a2017-12-19 12:23:48 +000020
Sam McCalla4962cc2018-04-27 11:59:28 +000021// 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.
27template <typename Callback>
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000028static bool iterateCodepoints(llvm::StringRef U8, const Callback &CB) {
Sam McCalla4962cc2018-04-27 11:59:28 +000029 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 Biryukovf2001aa2019-01-07 15:45:19 +000038 size_t UTF8Length = llvm::countLeadingOnes(C);
Sam McCalla4962cc2018-04-27 11:59:28 +000039 // 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 Biryukovf2001aa2019-01-07 15:45:19 +000055static size_t measureUTF16(llvm::StringRef U8, int U16Units, bool &Valid) {
Sam McCalla4962cc2018-04-27 11:59:28 +000056 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 McCalla4962cc2018-04-27 11:59:28 +000068// Like most strings in clangd, the input is UTF-8 encoded.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000069size_t lspLength(llvm::StringRef Code) {
Sam McCalla4962cc2018-04-27 11:59:28 +000070 // 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 McCall71891122018-10-23 11:51:53 +000073 iterateCodepoints(Code, [&](int U8Len, int U16Len) {
Sam McCalla4962cc2018-04-27 11:59:28 +000074 Count += U16Len;
75 return false;
76 });
77 return Count;
78}
79
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000080llvm::Expected<size_t> positionToOffset(llvm::StringRef Code, Position P,
81 bool AllowColumnsBeyondLineLength) {
Sam McCallb536a2a2017-12-19 12:23:48 +000082 if (P.line < 0)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000083 return llvm::make_error<llvm::StringError>(
84 llvm::formatv("Line value can't be negative ({0})", P.line),
85 llvm::errc::invalid_argument);
Simon Marchi766338a2018-03-21 14:36:46 +000086 if (P.character < 0)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000087 return llvm::make_error<llvm::StringError>(
88 llvm::formatv("Character value can't be negative ({0})", P.character),
89 llvm::errc::invalid_argument);
Sam McCallb536a2a2017-12-19 12:23:48 +000090 size_t StartOfLine = 0;
91 for (int I = 0; I != P.line; ++I) {
92 size_t NextNL = Code.find('\n', StartOfLine);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000093 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 McCallb536a2a2017-12-19 12:23:48 +000097 StartOfLine = NextNL + 1;
98 }
Simon Marchi766338a2018-03-21 14:36:46 +000099
100 size_t NextNL = Code.find('\n', StartOfLine);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000101 if (NextNL == llvm::StringRef::npos)
Simon Marchi766338a2018-03-21 14:36:46 +0000102 NextNL = Code.size();
103
Sam McCalla4962cc2018-04-27 11:59:28 +0000104 bool Valid;
105 size_t ByteOffsetInLine = measureUTF16(
106 Code.substr(StartOfLine, NextNL - StartOfLine), P.character, Valid);
107 if (!Valid && !AllowColumnsBeyondLineLength)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000108 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 McCalla4962cc2018-04-27 11:59:28 +0000112 return StartOfLine + ByteOffsetInLine;
Sam McCallb536a2a2017-12-19 12:23:48 +0000113}
114
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000115Position offsetToPosition(llvm::StringRef Code, size_t Offset) {
Sam McCallb536a2a2017-12-19 12:23:48 +0000116 Offset = std::min(Code.size(), Offset);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000117 llvm::StringRef Before = Code.substr(0, Offset);
Sam McCallb536a2a2017-12-19 12:23:48 +0000118 int Lines = Before.count('\n');
119 size_t PrevNL = Before.rfind('\n');
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000120 size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
Ilya Biryukov7beea3a2018-02-14 10:52:04 +0000121 Position Pos;
122 Pos.line = Lines;
Sam McCall71891122018-10-23 11:51:53 +0000123 Pos.character = lspLength(Before.substr(StartOfLine));
Ilya Biryukov7beea3a2018-02-14 10:52:04 +0000124 return Pos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000125}
126
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000127Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc) {
Sam McCalla4962cc2018-04-27 11:59:28 +0000128 // 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 Laperle63a10982018-02-21 02:39:08 +0000132 Position P;
Sam McCalla4962cc2018-04-27 11:59:28 +0000133 P.line = static_cast<int>(SM.getLineNumber(FID, Offset)) - 1;
134 bool Invalid = false;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000135 llvm::StringRef Code = SM.getBufferData(FID, &Invalid);
Sam McCalla4962cc2018-04-27 11:59:28 +0000136 if (!Invalid) {
137 auto ColumnInBytes = SM.getColumnNumber(FID, Offset) - 1;
138 auto LineSoFar = Code.substr(Offset - ColumnInBytes, ColumnInBytes);
Sam McCall71891122018-10-23 11:51:53 +0000139 P.character = lspLength(LineSoFar);
Sam McCalla4962cc2018-04-27 11:59:28 +0000140 }
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000141 return P;
142}
143
Ilya Biryukov71028b82018-03-12 15:28:22 +0000144Range 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 Biryukovf2001aa2019-01-07 15:45:19 +0000152std::pair<size_t, size_t> offsetToClangLineColumn(llvm::StringRef Code,
Sam McCalla4962cc2018-04-27 11:59:28 +0000153 size_t Offset) {
154 Offset = std::min(Code.size(), Offset);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000155 llvm::StringRef Before = Code.substr(0, Offset);
Sam McCalla4962cc2018-04-27 11:59:28 +0000156 int Lines = Before.count('\n');
157 size_t PrevNL = Before.rfind('\n');
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000158 size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
Sam McCalla4962cc2018-04-27 11:59:28 +0000159 return {Lines + 1, Offset - StartOfLine + 1};
160}
161
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000162std::pair<llvm::StringRef, llvm::StringRef>
163splitQualifiedName(llvm::StringRef QName) {
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000164 size_t Pos = QName.rfind("::");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000165 if (Pos == llvm::StringRef::npos)
166 return {llvm::StringRef(), QName};
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000167 return {QName.substr(0, Pos + 2), QName.substr(Pos + 2)};
168}
169
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000170TextEdit replacementToEdit(llvm::StringRef Code,
171 const tooling::Replacement &R) {
Eric Liu9133ecd2018-05-11 12:12:08 +0000172 Range ReplacementRange = {
173 offsetToPosition(Code, R.getOffset()),
174 offsetToPosition(Code, R.getOffset() + R.getLength())};
175 return {ReplacementRange, R.getReplacementText()};
176}
177
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000178std::vector<TextEdit> replacementsToEdits(llvm::StringRef Code,
Eric Liu9133ecd2018-05-11 12:12:08 +0000179 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 Biryukovf2001aa2019-01-07 15:45:19 +0000186llvm::Optional<std::string> getCanonicalPath(const FileEntry *F,
187 const SourceManager &SourceMgr) {
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000188 if (!F)
189 return None;
Simon Marchi25f1f732018-08-10 22:27:53 +0000190
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000191 llvm::SmallString<128> FilePath = F->getName();
192 if (!llvm::sys::path::is_absolute(FilePath)) {
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000193 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 McCallc008af62018-10-20 15:30:37 +0000198 return None;
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000199 }
200 }
Simon Marchi25f1f732018-08-10 22:27:53 +0000201
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000202 // 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 Biryukovf2001aa2019-01-07 15:45:19 +0000214 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 Cetinkayadd677932018-12-19 10:46:21 +0000219 return RealPath.str().str();
Simon Marchi25f1f732018-08-10 22:27:53 +0000220 }
221
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000222 return FilePath.str().str();
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000223}
224
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +0000225TextEdit 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 Wuaa3ed5a2019-01-25 15:14:03 +0000234bool isRangeConsecutive(const Range &Left, const Range &Right) {
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +0000235 return Left.end.line == Right.start.line &&
236 Left.end.character == Right.start.character;
237}
238
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000239FileDigest digest(llvm::StringRef Content) {
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000240 return llvm::SHA1::hash({(const uint8_t *)Content.data(), Content.size()});
241}
242
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000243llvm::Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID) {
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000244 bool Invalid = false;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000245 llvm::StringRef Content = SM.getBufferData(FID, &Invalid);
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000246 if (Invalid)
247 return None;
248 return digest(Content);
249}
250
Sam McCallb536a2a2017-12-19 12:23:48 +0000251} // namespace clangd
252} // namespace clang