blob: 656ab1dc3c1eba1d611965ad2e95760731edf55b [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
Sam McCalla69698f2019-03-27 17:47:49 +000010#include "Context.h"
Marc-Andre Laperle1be69702018-07-05 19:35:01 +000011#include "Logger.h"
Sam McCalla69698f2019-03-27 17:47:49 +000012#include "Protocol.h"
Marc-Andre Laperle1be69702018-07-05 19:35:01 +000013#include "clang/AST/ASTContext.h"
Marc-Andre Laperle63a10982018-02-21 02:39:08 +000014#include "clang/Basic/SourceManager.h"
Marc-Andre Laperle1be69702018-07-05 19:35:01 +000015#include "clang/Lex/Lexer.h"
Ilya Biryukov43998782019-01-31 21:30:05 +000016#include "llvm/ADT/None.h"
17#include "llvm/ADT/StringRef.h"
Simon Marchi766338a2018-03-21 14:36:46 +000018#include "llvm/Support/Errc.h"
19#include "llvm/Support/Error.h"
Sam McCall8b25d222019-03-28 14:37:51 +000020#include "llvm/Support/ErrorHandling.h"
Marc-Andre Laperle1be69702018-07-05 19:35:01 +000021#include "llvm/Support/Path.h"
Marc-Andre Laperle63a10982018-02-21 02:39:08 +000022
Sam McCallb536a2a2017-12-19 12:23:48 +000023namespace clang {
24namespace clangd {
Sam McCallb536a2a2017-12-19 12:23:48 +000025
Sam McCalla4962cc2018-04-27 11:59:28 +000026// Here be dragons. LSP positions use columns measured in *UTF-16 code units*!
27// Clangd uses UTF-8 and byte-offsets internally, so conversion is nontrivial.
28
29// Iterates over unicode codepoints in the (UTF-8) string. For each,
30// invokes CB(UTF-8 length, UTF-16 length), and breaks if it returns true.
31// Returns true if CB returned true, false if we hit the end of string.
32template <typename Callback>
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000033static bool iterateCodepoints(llvm::StringRef U8, const Callback &CB) {
Sam McCall8b25d222019-03-28 14:37:51 +000034 // A codepoint takes two UTF-16 code unit if it's astral (outside BMP).
35 // Astral codepoints are encoded as 4 bytes in UTF-8, starting with 11110xxx.
Sam McCalla4962cc2018-04-27 11:59:28 +000036 for (size_t I = 0; I < U8.size();) {
37 unsigned char C = static_cast<unsigned char>(U8[I]);
38 if (LLVM_LIKELY(!(C & 0x80))) { // ASCII character.
39 if (CB(1, 1))
40 return true;
41 ++I;
42 continue;
43 }
44 // This convenient property of UTF-8 holds for all non-ASCII characters.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000045 size_t UTF8Length = llvm::countLeadingOnes(C);
Sam McCalla4962cc2018-04-27 11:59:28 +000046 // 0xxx is ASCII, handled above. 10xxx is a trailing byte, invalid here.
47 // 11111xxx is not valid UTF-8 at all. Assert because it's probably our bug.
48 assert((UTF8Length >= 2 && UTF8Length <= 4) &&
49 "Invalid UTF-8, or transcoding bug?");
50 I += UTF8Length; // Skip over all trailing bytes.
51 // A codepoint takes two UTF-16 code unit if it's astral (outside BMP).
52 // Astral codepoints are encoded as 4 bytes in UTF-8 (11110xxx ...)
53 if (CB(UTF8Length, UTF8Length == 4 ? 2 : 1))
54 return true;
55 }
56 return false;
57}
58
Sam McCall8b25d222019-03-28 14:37:51 +000059// Returns the byte offset into the string that is an offset of \p Units in
60// the specified encoding.
61// Conceptually, this converts to the encoding, truncates to CodeUnits,
62// converts back to UTF-8, and returns the length in bytes.
63static size_t measureUnits(llvm::StringRef U8, int Units, OffsetEncoding Enc,
64 bool &Valid) {
65 Valid = Units >= 0;
66 if (Units <= 0)
67 return 0;
Sam McCalla4962cc2018-04-27 11:59:28 +000068 size_t Result = 0;
Sam McCall8b25d222019-03-28 14:37:51 +000069 switch (Enc) {
70 case OffsetEncoding::UTF8:
71 Result = Units;
72 break;
73 case OffsetEncoding::UTF16:
74 Valid = iterateCodepoints(U8, [&](int U8Len, int U16Len) {
75 Result += U8Len;
76 Units -= U16Len;
77 return Units <= 0;
78 });
79 if (Units < 0) // Offset in the middle of a surrogate pair.
80 Valid = false;
81 break;
82 case OffsetEncoding::UTF32:
83 Valid = iterateCodepoints(U8, [&](int U8Len, int U16Len) {
84 Result += U8Len;
85 Units--;
86 return Units <= 0;
87 });
88 break;
89 case OffsetEncoding::UnsupportedEncoding:
90 llvm_unreachable("unsupported encoding");
91 }
Sam McCalla4962cc2018-04-27 11:59:28 +000092 // Don't return an out-of-range index if we overran.
Sam McCall8b25d222019-03-28 14:37:51 +000093 if (Result > U8.size()) {
94 Valid = false;
95 return U8.size();
96 }
97 return Result;
Sam McCalla4962cc2018-04-27 11:59:28 +000098}
99
Sam McCalla69698f2019-03-27 17:47:49 +0000100Key<OffsetEncoding> kCurrentOffsetEncoding;
Sam McCall8b25d222019-03-28 14:37:51 +0000101static OffsetEncoding lspEncoding() {
Sam McCalla69698f2019-03-27 17:47:49 +0000102 auto *Enc = Context::current().get(kCurrentOffsetEncoding);
Sam McCall8b25d222019-03-28 14:37:51 +0000103 return Enc ? *Enc : OffsetEncoding::UTF16;
Sam McCalla69698f2019-03-27 17:47:49 +0000104}
105
Sam McCalla4962cc2018-04-27 11:59:28 +0000106// Like most strings in clangd, the input is UTF-8 encoded.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000107size_t lspLength(llvm::StringRef Code) {
Sam McCalla4962cc2018-04-27 11:59:28 +0000108 size_t Count = 0;
Sam McCall8b25d222019-03-28 14:37:51 +0000109 switch (lspEncoding()) {
110 case OffsetEncoding::UTF8:
111 Count = Code.size();
112 break;
113 case OffsetEncoding::UTF16:
114 iterateCodepoints(Code, [&](int U8Len, int U16Len) {
115 Count += U16Len;
116 return false;
117 });
118 break;
119 case OffsetEncoding::UTF32:
120 iterateCodepoints(Code, [&](int U8Len, int U16Len) {
121 ++Count;
122 return false;
123 });
124 break;
125 case OffsetEncoding::UnsupportedEncoding:
126 llvm_unreachable("unsupported encoding");
127 }
Sam McCalla4962cc2018-04-27 11:59:28 +0000128 return Count;
129}
130
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000131llvm::Expected<size_t> positionToOffset(llvm::StringRef Code, Position P,
132 bool AllowColumnsBeyondLineLength) {
Sam McCallb536a2a2017-12-19 12:23:48 +0000133 if (P.line < 0)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000134 return llvm::make_error<llvm::StringError>(
135 llvm::formatv("Line value can't be negative ({0})", P.line),
136 llvm::errc::invalid_argument);
Simon Marchi766338a2018-03-21 14:36:46 +0000137 if (P.character < 0)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000138 return llvm::make_error<llvm::StringError>(
139 llvm::formatv("Character value can't be negative ({0})", P.character),
140 llvm::errc::invalid_argument);
Sam McCallb536a2a2017-12-19 12:23:48 +0000141 size_t StartOfLine = 0;
142 for (int I = 0; I != P.line; ++I) {
143 size_t NextNL = Code.find('\n', StartOfLine);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000144 if (NextNL == llvm::StringRef::npos)
145 return llvm::make_error<llvm::StringError>(
146 llvm::formatv("Line value is out of range ({0})", P.line),
147 llvm::errc::invalid_argument);
Sam McCallb536a2a2017-12-19 12:23:48 +0000148 StartOfLine = NextNL + 1;
149 }
Sam McCalla69698f2019-03-27 17:47:49 +0000150 StringRef Line =
151 Code.substr(StartOfLine).take_until([](char C) { return C == '\n'; });
Simon Marchi766338a2018-03-21 14:36:46 +0000152
Sam McCall8b25d222019-03-28 14:37:51 +0000153 // P.character may be in UTF-16, transcode if necessary.
Sam McCalla4962cc2018-04-27 11:59:28 +0000154 bool Valid;
Sam McCall8b25d222019-03-28 14:37:51 +0000155 size_t ByteInLine = measureUnits(Line, P.character, lspEncoding(), Valid);
Sam McCalla4962cc2018-04-27 11:59:28 +0000156 if (!Valid && !AllowColumnsBeyondLineLength)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000157 return llvm::make_error<llvm::StringError>(
Sam McCall8b25d222019-03-28 14:37:51 +0000158 llvm::formatv("{0} offset {1} is invalid for line {2}", lspEncoding(),
159 P.character, P.line),
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000160 llvm::errc::invalid_argument);
Sam McCall8b25d222019-03-28 14:37:51 +0000161 return StartOfLine + ByteInLine;
Sam McCallb536a2a2017-12-19 12:23:48 +0000162}
163
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000164Position offsetToPosition(llvm::StringRef Code, size_t Offset) {
Sam McCallb536a2a2017-12-19 12:23:48 +0000165 Offset = std::min(Code.size(), Offset);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000166 llvm::StringRef Before = Code.substr(0, Offset);
Sam McCallb536a2a2017-12-19 12:23:48 +0000167 int Lines = Before.count('\n');
168 size_t PrevNL = Before.rfind('\n');
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000169 size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
Ilya Biryukov7beea3a2018-02-14 10:52:04 +0000170 Position Pos;
171 Pos.line = Lines;
Sam McCall71891122018-10-23 11:51:53 +0000172 Pos.character = lspLength(Before.substr(StartOfLine));
Ilya Biryukov7beea3a2018-02-14 10:52:04 +0000173 return Pos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000174}
175
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000176Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc) {
Sam McCalla4962cc2018-04-27 11:59:28 +0000177 // We use the SourceManager's line tables, but its column number is in bytes.
178 FileID FID;
179 unsigned Offset;
180 std::tie(FID, Offset) = SM.getDecomposedSpellingLoc(Loc);
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000181 Position P;
Sam McCalla4962cc2018-04-27 11:59:28 +0000182 P.line = static_cast<int>(SM.getLineNumber(FID, Offset)) - 1;
183 bool Invalid = false;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000184 llvm::StringRef Code = SM.getBufferData(FID, &Invalid);
Sam McCalla4962cc2018-04-27 11:59:28 +0000185 if (!Invalid) {
186 auto ColumnInBytes = SM.getColumnNumber(FID, Offset) - 1;
187 auto LineSoFar = Code.substr(Offset - ColumnInBytes, ColumnInBytes);
Sam McCall71891122018-10-23 11:51:53 +0000188 P.character = lspLength(LineSoFar);
Sam McCalla4962cc2018-04-27 11:59:28 +0000189 }
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000190 return P;
191}
192
Ilya Biryukov43998782019-01-31 21:30:05 +0000193bool isValidFileRange(const SourceManager &Mgr, SourceRange R) {
194 if (!R.getBegin().isValid() || !R.getEnd().isValid())
195 return false;
196
197 FileID BeginFID;
198 size_t BeginOffset = 0;
199 std::tie(BeginFID, BeginOffset) = Mgr.getDecomposedLoc(R.getBegin());
200
201 FileID EndFID;
202 size_t EndOffset = 0;
203 std::tie(EndFID, EndOffset) = Mgr.getDecomposedLoc(R.getEnd());
204
205 return BeginFID.isValid() && BeginFID == EndFID && BeginOffset <= EndOffset;
206}
207
208bool halfOpenRangeContains(const SourceManager &Mgr, SourceRange R,
209 SourceLocation L) {
210 assert(isValidFileRange(Mgr, R));
211
212 FileID BeginFID;
213 size_t BeginOffset = 0;
214 std::tie(BeginFID, BeginOffset) = Mgr.getDecomposedLoc(R.getBegin());
215 size_t EndOffset = Mgr.getFileOffset(R.getEnd());
216
217 FileID LFid;
218 size_t LOffset;
219 std::tie(LFid, LOffset) = Mgr.getDecomposedLoc(L);
220 return BeginFID == LFid && BeginOffset <= LOffset && LOffset < EndOffset;
221}
222
223bool halfOpenRangeTouches(const SourceManager &Mgr, SourceRange R,
224 SourceLocation L) {
225 return L == R.getEnd() || halfOpenRangeContains(Mgr, R, L);
226}
227
228llvm::Optional<SourceRange> toHalfOpenFileRange(const SourceManager &Mgr,
229 const LangOptions &LangOpts,
230 SourceRange R) {
231 auto Begin = Mgr.getFileLoc(R.getBegin());
232 if (Begin.isInvalid())
233 return llvm::None;
234 auto End = Mgr.getFileLoc(R.getEnd());
235 if (End.isInvalid())
236 return llvm::None;
237 End = Lexer::getLocForEndOfToken(End, 0, Mgr, LangOpts);
238
239 SourceRange Result(Begin, End);
240 if (!isValidFileRange(Mgr, Result))
241 return llvm::None;
242 return Result;
243}
244
245llvm::StringRef toSourceCode(const SourceManager &SM, SourceRange R) {
246 assert(isValidFileRange(SM, R));
247 bool Invalid = false;
248 auto *Buf = SM.getBuffer(SM.getFileID(R.getBegin()), &Invalid);
249 assert(!Invalid);
250
251 size_t BeginOffset = SM.getFileOffset(R.getBegin());
252 size_t EndOffset = SM.getFileOffset(R.getEnd());
253 return Buf->getBuffer().substr(BeginOffset, EndOffset - BeginOffset);
254}
255
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000256llvm::Expected<SourceLocation> sourceLocationInMainFile(const SourceManager &SM,
257 Position P) {
258 llvm::StringRef Code = SM.getBuffer(SM.getMainFileID())->getBuffer();
259 auto Offset =
260 positionToOffset(Code, P, /*AllowColumnBeyondLineLength=*/false);
261 if (!Offset)
262 return Offset.takeError();
263 return SM.getLocForStartOfFile(SM.getMainFileID()).getLocWithOffset(*Offset);
264}
265
Ilya Biryukov71028b82018-03-12 15:28:22 +0000266Range halfOpenToRange(const SourceManager &SM, CharSourceRange R) {
267 // Clang is 1-based, LSP uses 0-based indexes.
268 Position Begin = sourceLocToPosition(SM, R.getBegin());
269 Position End = sourceLocToPosition(SM, R.getEnd());
270
271 return {Begin, End};
272}
273
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000274std::pair<size_t, size_t> offsetToClangLineColumn(llvm::StringRef Code,
Sam McCalla4962cc2018-04-27 11:59:28 +0000275 size_t Offset) {
276 Offset = std::min(Code.size(), Offset);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000277 llvm::StringRef Before = Code.substr(0, Offset);
Sam McCalla4962cc2018-04-27 11:59:28 +0000278 int Lines = Before.count('\n');
279 size_t PrevNL = Before.rfind('\n');
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000280 size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
Sam McCalla4962cc2018-04-27 11:59:28 +0000281 return {Lines + 1, Offset - StartOfLine + 1};
282}
283
Ilya Biryukov43998782019-01-31 21:30:05 +0000284std::pair<StringRef, StringRef> splitQualifiedName(StringRef QName) {
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000285 size_t Pos = QName.rfind("::");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000286 if (Pos == llvm::StringRef::npos)
287 return {llvm::StringRef(), QName};
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000288 return {QName.substr(0, Pos + 2), QName.substr(Pos + 2)};
289}
290
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000291TextEdit replacementToEdit(llvm::StringRef Code,
292 const tooling::Replacement &R) {
Eric Liu9133ecd2018-05-11 12:12:08 +0000293 Range ReplacementRange = {
294 offsetToPosition(Code, R.getOffset()),
295 offsetToPosition(Code, R.getOffset() + R.getLength())};
296 return {ReplacementRange, R.getReplacementText()};
297}
298
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000299std::vector<TextEdit> replacementsToEdits(llvm::StringRef Code,
Eric Liu9133ecd2018-05-11 12:12:08 +0000300 const tooling::Replacements &Repls) {
301 std::vector<TextEdit> Edits;
302 for (const auto &R : Repls)
303 Edits.push_back(replacementToEdit(Code, R));
304 return Edits;
305}
306
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000307llvm::Optional<std::string> getCanonicalPath(const FileEntry *F,
308 const SourceManager &SourceMgr) {
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000309 if (!F)
310 return None;
Simon Marchi25f1f732018-08-10 22:27:53 +0000311
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000312 llvm::SmallString<128> FilePath = F->getName();
313 if (!llvm::sys::path::is_absolute(FilePath)) {
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000314 if (auto EC =
Duncan P. N. Exon Smithdb8a7422019-03-26 22:32:06 +0000315 SourceMgr.getFileManager().getVirtualFileSystem().makeAbsolute(
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000316 FilePath)) {
317 elog("Could not turn relative path '{0}' to absolute: {1}", FilePath,
318 EC.message());
Sam McCallc008af62018-10-20 15:30:37 +0000319 return None;
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000320 }
321 }
Simon Marchi25f1f732018-08-10 22:27:53 +0000322
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000323 // Handle the symbolic link path case where the current working directory
324 // (getCurrentWorkingDirectory) is a symlink./ We always want to the real
325 // file path (instead of the symlink path) for the C++ symbols.
326 //
327 // Consider the following example:
328 //
329 // src dir: /project/src/foo.h
330 // current working directory (symlink): /tmp/build -> /project/src/
331 //
332 // The file path of Symbol is "/project/src/foo.h" instead of
333 // "/tmp/build/foo.h"
334 if (const DirectoryEntry *Dir = SourceMgr.getFileManager().getDirectory(
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000335 llvm::sys::path::parent_path(FilePath))) {
336 llvm::SmallString<128> RealPath;
337 llvm::StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir);
338 llvm::sys::path::append(RealPath, DirName,
339 llvm::sys::path::filename(FilePath));
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000340 return RealPath.str().str();
Simon Marchi25f1f732018-08-10 22:27:53 +0000341 }
342
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000343 return FilePath.str().str();
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000344}
345
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +0000346TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M,
347 const LangOptions &L) {
348 TextEdit Result;
349 Result.range =
350 halfOpenToRange(M, Lexer::makeFileCharRange(FixIt.RemoveRange, M, L));
351 Result.newText = FixIt.CodeToInsert;
352 return Result;
353}
354
Haojian Wuaa3ed5a2019-01-25 15:14:03 +0000355bool isRangeConsecutive(const Range &Left, const Range &Right) {
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +0000356 return Left.end.line == Right.start.line &&
357 Left.end.character == Right.start.character;
358}
359
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000360FileDigest digest(llvm::StringRef Content) {
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000361 return llvm::SHA1::hash({(const uint8_t *)Content.data(), Content.size()});
362}
363
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000364llvm::Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID) {
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000365 bool Invalid = false;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000366 llvm::StringRef Content = SM.getBufferData(FID, &Invalid);
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000367 if (Invalid)
368 return None;
369 return digest(Content);
370}
371
Eric Liudd662772019-01-28 14:01:55 +0000372format::FormatStyle getFormatStyleForFile(llvm::StringRef File,
373 llvm::StringRef Content,
374 llvm::vfs::FileSystem *FS) {
375 auto Style = format::getStyle(format::DefaultFormatStyle, File,
376 format::DefaultFallbackStyle, Content, FS);
377 if (!Style) {
378 log("getStyle() failed for file {0}: {1}. Fallback is LLVM style.", File,
379 Style.takeError());
380 Style = format::getLLVMStyle();
381 }
382 return *Style;
383}
384
Haojian Wu12e194c2019-02-06 15:24:50 +0000385llvm::Expected<tooling::Replacements>
386cleanupAndFormat(StringRef Code, const tooling::Replacements &Replaces,
387 const format::FormatStyle &Style) {
388 auto CleanReplaces = cleanupAroundReplacements(Code, Replaces, Style);
389 if (!CleanReplaces)
390 return CleanReplaces;
391 return formatReplacements(Code, std::move(*CleanReplaces), Style);
392}
393
Sam McCallb536a2a2017-12-19 12:23:48 +0000394} // namespace clangd
395} // namespace clang