blob: fb1183aef5115ccb6c76c7ff5160c8d8ae72c082 [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"
Sam McCall9fb22b22019-05-06 10:25:10 +000011#include "FuzzyMatch.h"
Marc-Andre Laperle1be69702018-07-05 19:35:01 +000012#include "Logger.h"
Sam McCalla69698f2019-03-27 17:47:49 +000013#include "Protocol.h"
Marc-Andre Laperle1be69702018-07-05 19:35:01 +000014#include "clang/AST/ASTContext.h"
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +000015#include "clang/Basic/LangOptions.h"
16#include "clang/Basic/SourceLocation.h"
Marc-Andre Laperle63a10982018-02-21 02:39:08 +000017#include "clang/Basic/SourceManager.h"
Sam McCallc316b222019-04-26 07:45:49 +000018#include "clang/Basic/TokenKinds.h"
19#include "clang/Format/Format.h"
Marc-Andre Laperle1be69702018-07-05 19:35:01 +000020#include "clang/Lex/Lexer.h"
Haojian Wu9d34f452019-07-01 09:26:48 +000021#include "clang/Lex/Preprocessor.h"
Ilya Biryukov43998782019-01-31 21:30:05 +000022#include "llvm/ADT/None.h"
Sam McCallc316b222019-04-26 07:45:49 +000023#include "llvm/ADT/StringExtras.h"
Ilya Biryukov43998782019-01-31 21:30:05 +000024#include "llvm/ADT/StringRef.h"
Sam McCall9fb22b22019-05-06 10:25:10 +000025#include "llvm/Support/Compiler.h"
Simon Marchi766338a2018-03-21 14:36:46 +000026#include "llvm/Support/Errc.h"
27#include "llvm/Support/Error.h"
Sam McCall8b25d222019-03-28 14:37:51 +000028#include "llvm/Support/ErrorHandling.h"
Marc-Andre Laperle1be69702018-07-05 19:35:01 +000029#include "llvm/Support/Path.h"
Sam McCall674d8a92019-07-08 11:33:17 +000030#include "llvm/Support/xxhash.h"
Sam McCallc316b222019-04-26 07:45:49 +000031#include <algorithm>
Marc-Andre Laperle63a10982018-02-21 02:39:08 +000032
Sam McCallb536a2a2017-12-19 12:23:48 +000033namespace clang {
34namespace clangd {
Sam McCallb536a2a2017-12-19 12:23:48 +000035
Sam McCalla4962cc2018-04-27 11:59:28 +000036// Here be dragons. LSP positions use columns measured in *UTF-16 code units*!
37// Clangd uses UTF-8 and byte-offsets internally, so conversion is nontrivial.
38
39// Iterates over unicode codepoints in the (UTF-8) string. For each,
40// invokes CB(UTF-8 length, UTF-16 length), and breaks if it returns true.
41// Returns true if CB returned true, false if we hit the end of string.
42template <typename Callback>
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000043static bool iterateCodepoints(llvm::StringRef U8, const Callback &CB) {
Sam McCall8b25d222019-03-28 14:37:51 +000044 // 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, starting with 11110xxx.
Sam McCalla4962cc2018-04-27 11:59:28 +000046 for (size_t I = 0; I < U8.size();) {
47 unsigned char C = static_cast<unsigned char>(U8[I]);
48 if (LLVM_LIKELY(!(C & 0x80))) { // ASCII character.
49 if (CB(1, 1))
50 return true;
51 ++I;
52 continue;
53 }
54 // This convenient property of UTF-8 holds for all non-ASCII characters.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000055 size_t UTF8Length = llvm::countLeadingOnes(C);
Sam McCalla4962cc2018-04-27 11:59:28 +000056 // 0xxx is ASCII, handled above. 10xxx is a trailing byte, invalid here.
57 // 11111xxx is not valid UTF-8 at all. Assert because it's probably our bug.
58 assert((UTF8Length >= 2 && UTF8Length <= 4) &&
59 "Invalid UTF-8, or transcoding bug?");
60 I += UTF8Length; // Skip over all trailing bytes.
61 // A codepoint takes two UTF-16 code unit if it's astral (outside BMP).
62 // Astral codepoints are encoded as 4 bytes in UTF-8 (11110xxx ...)
63 if (CB(UTF8Length, UTF8Length == 4 ? 2 : 1))
64 return true;
65 }
66 return false;
67}
68
Sam McCall8b25d222019-03-28 14:37:51 +000069// Returns the byte offset into the string that is an offset of \p Units in
70// the specified encoding.
71// Conceptually, this converts to the encoding, truncates to CodeUnits,
72// converts back to UTF-8, and returns the length in bytes.
73static size_t measureUnits(llvm::StringRef U8, int Units, OffsetEncoding Enc,
74 bool &Valid) {
75 Valid = Units >= 0;
76 if (Units <= 0)
77 return 0;
Sam McCalla4962cc2018-04-27 11:59:28 +000078 size_t Result = 0;
Sam McCall8b25d222019-03-28 14:37:51 +000079 switch (Enc) {
80 case OffsetEncoding::UTF8:
81 Result = Units;
82 break;
83 case OffsetEncoding::UTF16:
84 Valid = iterateCodepoints(U8, [&](int U8Len, int U16Len) {
85 Result += U8Len;
86 Units -= U16Len;
87 return Units <= 0;
88 });
89 if (Units < 0) // Offset in the middle of a surrogate pair.
90 Valid = false;
91 break;
92 case OffsetEncoding::UTF32:
93 Valid = iterateCodepoints(U8, [&](int U8Len, int U16Len) {
94 Result += U8Len;
95 Units--;
96 return Units <= 0;
97 });
98 break;
99 case OffsetEncoding::UnsupportedEncoding:
100 llvm_unreachable("unsupported encoding");
101 }
Sam McCalla4962cc2018-04-27 11:59:28 +0000102 // Don't return an out-of-range index if we overran.
Sam McCall8b25d222019-03-28 14:37:51 +0000103 if (Result > U8.size()) {
104 Valid = false;
105 return U8.size();
106 }
107 return Result;
Sam McCalla4962cc2018-04-27 11:59:28 +0000108}
109
Sam McCalla69698f2019-03-27 17:47:49 +0000110Key<OffsetEncoding> kCurrentOffsetEncoding;
Sam McCall8b25d222019-03-28 14:37:51 +0000111static OffsetEncoding lspEncoding() {
Sam McCalla69698f2019-03-27 17:47:49 +0000112 auto *Enc = Context::current().get(kCurrentOffsetEncoding);
Sam McCall8b25d222019-03-28 14:37:51 +0000113 return Enc ? *Enc : OffsetEncoding::UTF16;
Sam McCalla69698f2019-03-27 17:47:49 +0000114}
115
Sam McCalla4962cc2018-04-27 11:59:28 +0000116// Like most strings in clangd, the input is UTF-8 encoded.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000117size_t lspLength(llvm::StringRef Code) {
Sam McCalla4962cc2018-04-27 11:59:28 +0000118 size_t Count = 0;
Sam McCall8b25d222019-03-28 14:37:51 +0000119 switch (lspEncoding()) {
120 case OffsetEncoding::UTF8:
121 Count = Code.size();
122 break;
123 case OffsetEncoding::UTF16:
124 iterateCodepoints(Code, [&](int U8Len, int U16Len) {
125 Count += U16Len;
126 return false;
127 });
128 break;
129 case OffsetEncoding::UTF32:
130 iterateCodepoints(Code, [&](int U8Len, int U16Len) {
131 ++Count;
132 return false;
133 });
134 break;
135 case OffsetEncoding::UnsupportedEncoding:
136 llvm_unreachable("unsupported encoding");
137 }
Sam McCalla4962cc2018-04-27 11:59:28 +0000138 return Count;
139}
140
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000141llvm::Expected<size_t> positionToOffset(llvm::StringRef Code, Position P,
142 bool AllowColumnsBeyondLineLength) {
Sam McCallb536a2a2017-12-19 12:23:48 +0000143 if (P.line < 0)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000144 return llvm::make_error<llvm::StringError>(
145 llvm::formatv("Line value can't be negative ({0})", P.line),
146 llvm::errc::invalid_argument);
Simon Marchi766338a2018-03-21 14:36:46 +0000147 if (P.character < 0)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000148 return llvm::make_error<llvm::StringError>(
149 llvm::formatv("Character value can't be negative ({0})", P.character),
150 llvm::errc::invalid_argument);
Sam McCallb536a2a2017-12-19 12:23:48 +0000151 size_t StartOfLine = 0;
152 for (int I = 0; I != P.line; ++I) {
153 size_t NextNL = Code.find('\n', StartOfLine);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000154 if (NextNL == llvm::StringRef::npos)
155 return llvm::make_error<llvm::StringError>(
156 llvm::formatv("Line value is out of range ({0})", P.line),
157 llvm::errc::invalid_argument);
Sam McCallb536a2a2017-12-19 12:23:48 +0000158 StartOfLine = NextNL + 1;
159 }
Sam McCalla69698f2019-03-27 17:47:49 +0000160 StringRef Line =
161 Code.substr(StartOfLine).take_until([](char C) { return C == '\n'; });
Simon Marchi766338a2018-03-21 14:36:46 +0000162
Sam McCall8b25d222019-03-28 14:37:51 +0000163 // P.character may be in UTF-16, transcode if necessary.
Sam McCalla4962cc2018-04-27 11:59:28 +0000164 bool Valid;
Sam McCall8b25d222019-03-28 14:37:51 +0000165 size_t ByteInLine = measureUnits(Line, P.character, lspEncoding(), Valid);
Sam McCalla4962cc2018-04-27 11:59:28 +0000166 if (!Valid && !AllowColumnsBeyondLineLength)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000167 return llvm::make_error<llvm::StringError>(
Sam McCall8b25d222019-03-28 14:37:51 +0000168 llvm::formatv("{0} offset {1} is invalid for line {2}", lspEncoding(),
169 P.character, P.line),
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000170 llvm::errc::invalid_argument);
Sam McCall8b25d222019-03-28 14:37:51 +0000171 return StartOfLine + ByteInLine;
Sam McCallb536a2a2017-12-19 12:23:48 +0000172}
173
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000174Position offsetToPosition(llvm::StringRef Code, size_t Offset) {
Sam McCallb536a2a2017-12-19 12:23:48 +0000175 Offset = std::min(Code.size(), Offset);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000176 llvm::StringRef Before = Code.substr(0, Offset);
Sam McCallb536a2a2017-12-19 12:23:48 +0000177 int Lines = Before.count('\n');
178 size_t PrevNL = Before.rfind('\n');
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000179 size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
Ilya Biryukov7beea3a2018-02-14 10:52:04 +0000180 Position Pos;
181 Pos.line = Lines;
Sam McCall71891122018-10-23 11:51:53 +0000182 Pos.character = lspLength(Before.substr(StartOfLine));
Ilya Biryukov7beea3a2018-02-14 10:52:04 +0000183 return Pos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000184}
185
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000186Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc) {
Sam McCalla4962cc2018-04-27 11:59:28 +0000187 // We use the SourceManager's line tables, but its column number is in bytes.
188 FileID FID;
189 unsigned Offset;
190 std::tie(FID, Offset) = SM.getDecomposedSpellingLoc(Loc);
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000191 Position P;
Sam McCalla4962cc2018-04-27 11:59:28 +0000192 P.line = static_cast<int>(SM.getLineNumber(FID, Offset)) - 1;
193 bool Invalid = false;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000194 llvm::StringRef Code = SM.getBufferData(FID, &Invalid);
Sam McCalla4962cc2018-04-27 11:59:28 +0000195 if (!Invalid) {
196 auto ColumnInBytes = SM.getColumnNumber(FID, Offset) - 1;
197 auto LineSoFar = Code.substr(Offset - ColumnInBytes, ColumnInBytes);
Sam McCall71891122018-10-23 11:51:53 +0000198 P.character = lspLength(LineSoFar);
Sam McCalla4962cc2018-04-27 11:59:28 +0000199 }
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000200 return P;
201}
202
Haojian Wu92c32572019-06-25 08:01:46 +0000203llvm::Optional<Range> getTokenRange(const SourceManager &SM,
204 const LangOptions &LangOpts,
205 SourceLocation TokLoc) {
206 if (!TokLoc.isValid())
207 return llvm::None;
208 SourceLocation End = Lexer::getLocForEndOfToken(TokLoc, 0, SM, LangOpts);
209 if (!End.isValid())
210 return llvm::None;
211 return halfOpenToRange(SM, CharSourceRange::getCharRange(TokLoc, End));
212}
213
Ilya Biryukov43998782019-01-31 21:30:05 +0000214bool isValidFileRange(const SourceManager &Mgr, SourceRange R) {
215 if (!R.getBegin().isValid() || !R.getEnd().isValid())
216 return false;
217
218 FileID BeginFID;
219 size_t BeginOffset = 0;
220 std::tie(BeginFID, BeginOffset) = Mgr.getDecomposedLoc(R.getBegin());
221
222 FileID EndFID;
223 size_t EndOffset = 0;
224 std::tie(EndFID, EndOffset) = Mgr.getDecomposedLoc(R.getEnd());
225
226 return BeginFID.isValid() && BeginFID == EndFID && BeginOffset <= EndOffset;
227}
228
229bool halfOpenRangeContains(const SourceManager &Mgr, SourceRange R,
230 SourceLocation L) {
231 assert(isValidFileRange(Mgr, R));
232
233 FileID BeginFID;
234 size_t BeginOffset = 0;
235 std::tie(BeginFID, BeginOffset) = Mgr.getDecomposedLoc(R.getBegin());
236 size_t EndOffset = Mgr.getFileOffset(R.getEnd());
237
238 FileID LFid;
239 size_t LOffset;
240 std::tie(LFid, LOffset) = Mgr.getDecomposedLoc(L);
241 return BeginFID == LFid && BeginOffset <= LOffset && LOffset < EndOffset;
242}
243
244bool halfOpenRangeTouches(const SourceManager &Mgr, SourceRange R,
245 SourceLocation L) {
246 return L == R.getEnd() || halfOpenRangeContains(Mgr, R, L);
247}
248
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000249static unsigned getTokenLengthAtLoc(SourceLocation Loc, const SourceManager &SM,
250 const LangOptions &LangOpts) {
251 Token TheTok;
252 if (Lexer::getRawToken(Loc, TheTok, SM, LangOpts))
253 return 0;
254 // FIXME: Here we check whether the token at the location is a greatergreater
255 // (>>) token and consider it as a single greater (>). This is to get it
256 // working for templates but it isn't correct for the right shift operator. We
257 // can avoid this by using half open char ranges in getFileRange() but getting
258 // token ending is not well supported in macroIDs.
259 if (TheTok.is(tok::greatergreater))
260 return 1;
261 return TheTok.getLength();
262}
263
264// Returns location of the last character of the token at a given loc
265static SourceLocation getLocForTokenEnd(SourceLocation BeginLoc,
266 const SourceManager &SM,
267 const LangOptions &LangOpts) {
268 unsigned Len = getTokenLengthAtLoc(BeginLoc, SM, LangOpts);
269 return BeginLoc.getLocWithOffset(Len ? Len - 1 : 0);
270}
271
272// Returns location of the starting of the token at a given EndLoc
273static SourceLocation getLocForTokenBegin(SourceLocation EndLoc,
274 const SourceManager &SM,
275 const LangOptions &LangOpts) {
276 return EndLoc.getLocWithOffset(
277 -(signed)getTokenLengthAtLoc(EndLoc, SM, LangOpts));
278}
279
280// Converts a char source range to a token range.
281static SourceRange toTokenRange(CharSourceRange Range, const SourceManager &SM,
282 const LangOptions &LangOpts) {
283 if (!Range.isTokenRange())
284 Range.setEnd(getLocForTokenBegin(Range.getEnd(), SM, LangOpts));
285 return Range.getAsRange();
286}
287// Returns the union of two token ranges.
288// To find the maximum of the Ends of the ranges, we compare the location of the
289// last character of the token.
290static SourceRange unionTokenRange(SourceRange R1, SourceRange R2,
291 const SourceManager &SM,
292 const LangOptions &LangOpts) {
293 SourceLocation E1 = getLocForTokenEnd(R1.getEnd(), SM, LangOpts);
294 SourceLocation E2 = getLocForTokenEnd(R2.getEnd(), SM, LangOpts);
295 return SourceRange(std::min(R1.getBegin(), R2.getBegin()),
296 E1 < E2 ? R2.getEnd() : R1.getEnd());
297}
298
299// Returns the tokenFileRange for a given Location as a Token Range
300// This is quite similar to getFileLoc in SourceManager as both use
301// getImmediateExpansionRange and getImmediateSpellingLoc (for macro IDs).
302// However:
303// - We want to maintain the full range information as we move from one file to
304// the next. getFileLoc only uses the BeginLoc of getImmediateExpansionRange.
305// - We want to split '>>' tokens as the lexer parses the '>>' in template
306// instantiations as a '>>' instead of a '>'.
307// There is also getExpansionRange but it simply calls
308// getImmediateExpansionRange on the begin and ends separately which is wrong.
309static SourceRange getTokenFileRange(SourceLocation Loc,
310 const SourceManager &SM,
311 const LangOptions &LangOpts) {
312 SourceRange FileRange = Loc;
313 while (!FileRange.getBegin().isFileID()) {
314 assert(!FileRange.getEnd().isFileID() &&
315 "Both Begin and End should be MacroIDs.");
316 if (SM.isMacroArgExpansion(FileRange.getBegin())) {
317 FileRange.setBegin(SM.getImmediateSpellingLoc(FileRange.getBegin()));
318 FileRange.setEnd(SM.getImmediateSpellingLoc(FileRange.getEnd()));
319 } else {
320 SourceRange ExpansionRangeForBegin = toTokenRange(
321 SM.getImmediateExpansionRange(FileRange.getBegin()), SM, LangOpts);
322 SourceRange ExpansionRangeForEnd = toTokenRange(
323 SM.getImmediateExpansionRange(FileRange.getEnd()), SM, LangOpts);
324 FileRange = unionTokenRange(ExpansionRangeForBegin, ExpansionRangeForEnd,
325 SM, LangOpts);
326 }
327 }
328 return FileRange;
329}
330
331llvm::Optional<SourceRange> toHalfOpenFileRange(const SourceManager &SM,
Ilya Biryukov43998782019-01-31 21:30:05 +0000332 const LangOptions &LangOpts,
333 SourceRange R) {
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000334 SourceRange R1 = getTokenFileRange(R.getBegin(), SM, LangOpts);
335 if (!isValidFileRange(SM, R1))
Ilya Biryukov43998782019-01-31 21:30:05 +0000336 return llvm::None;
Ilya Biryukov43998782019-01-31 21:30:05 +0000337
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000338 SourceRange R2 = getTokenFileRange(R.getEnd(), SM, LangOpts);
339 if (!isValidFileRange(SM, R2))
Ilya Biryukov43998782019-01-31 21:30:05 +0000340 return llvm::None;
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000341
342 SourceRange Result = unionTokenRange(R1, R2, SM, LangOpts);
343 unsigned TokLen = getTokenLengthAtLoc(Result.getEnd(), SM, LangOpts);
344 // Convert from closed token range to half-open (char) range
345 Result.setEnd(Result.getEnd().getLocWithOffset(TokLen));
346 if (!isValidFileRange(SM, Result))
347 return llvm::None;
348
Ilya Biryukov43998782019-01-31 21:30:05 +0000349 return Result;
350}
351
352llvm::StringRef toSourceCode(const SourceManager &SM, SourceRange R) {
353 assert(isValidFileRange(SM, R));
354 bool Invalid = false;
355 auto *Buf = SM.getBuffer(SM.getFileID(R.getBegin()), &Invalid);
356 assert(!Invalid);
357
358 size_t BeginOffset = SM.getFileOffset(R.getBegin());
359 size_t EndOffset = SM.getFileOffset(R.getEnd());
360 return Buf->getBuffer().substr(BeginOffset, EndOffset - BeginOffset);
361}
362
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000363llvm::Expected<SourceLocation> sourceLocationInMainFile(const SourceManager &SM,
364 Position P) {
365 llvm::StringRef Code = SM.getBuffer(SM.getMainFileID())->getBuffer();
366 auto Offset =
367 positionToOffset(Code, P, /*AllowColumnBeyondLineLength=*/false);
368 if (!Offset)
369 return Offset.takeError();
370 return SM.getLocForStartOfFile(SM.getMainFileID()).getLocWithOffset(*Offset);
371}
372
Ilya Biryukov71028b82018-03-12 15:28:22 +0000373Range halfOpenToRange(const SourceManager &SM, CharSourceRange R) {
374 // Clang is 1-based, LSP uses 0-based indexes.
375 Position Begin = sourceLocToPosition(SM, R.getBegin());
376 Position End = sourceLocToPosition(SM, R.getEnd());
377
378 return {Begin, End};
379}
380
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000381std::pair<size_t, size_t> offsetToClangLineColumn(llvm::StringRef Code,
Sam McCalla4962cc2018-04-27 11:59:28 +0000382 size_t Offset) {
383 Offset = std::min(Code.size(), Offset);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000384 llvm::StringRef Before = Code.substr(0, Offset);
Sam McCalla4962cc2018-04-27 11:59:28 +0000385 int Lines = Before.count('\n');
386 size_t PrevNL = Before.rfind('\n');
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000387 size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
Sam McCalla4962cc2018-04-27 11:59:28 +0000388 return {Lines + 1, Offset - StartOfLine + 1};
389}
390
Ilya Biryukov43998782019-01-31 21:30:05 +0000391std::pair<StringRef, StringRef> splitQualifiedName(StringRef QName) {
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000392 size_t Pos = QName.rfind("::");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000393 if (Pos == llvm::StringRef::npos)
394 return {llvm::StringRef(), QName};
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000395 return {QName.substr(0, Pos + 2), QName.substr(Pos + 2)};
396}
397
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000398TextEdit replacementToEdit(llvm::StringRef Code,
399 const tooling::Replacement &R) {
Eric Liu9133ecd2018-05-11 12:12:08 +0000400 Range ReplacementRange = {
401 offsetToPosition(Code, R.getOffset()),
402 offsetToPosition(Code, R.getOffset() + R.getLength())};
403 return {ReplacementRange, R.getReplacementText()};
404}
405
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000406std::vector<TextEdit> replacementsToEdits(llvm::StringRef Code,
Eric Liu9133ecd2018-05-11 12:12:08 +0000407 const tooling::Replacements &Repls) {
408 std::vector<TextEdit> Edits;
409 for (const auto &R : Repls)
410 Edits.push_back(replacementToEdit(Code, R));
411 return Edits;
412}
413
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000414llvm::Optional<std::string> getCanonicalPath(const FileEntry *F,
415 const SourceManager &SourceMgr) {
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000416 if (!F)
417 return None;
Simon Marchi25f1f732018-08-10 22:27:53 +0000418
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000419 llvm::SmallString<128> FilePath = F->getName();
420 if (!llvm::sys::path::is_absolute(FilePath)) {
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000421 if (auto EC =
Duncan P. N. Exon Smithdb8a7422019-03-26 22:32:06 +0000422 SourceMgr.getFileManager().getVirtualFileSystem().makeAbsolute(
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000423 FilePath)) {
424 elog("Could not turn relative path '{0}' to absolute: {1}", FilePath,
425 EC.message());
Sam McCallc008af62018-10-20 15:30:37 +0000426 return None;
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000427 }
428 }
Simon Marchi25f1f732018-08-10 22:27:53 +0000429
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000430 // Handle the symbolic link path case where the current working directory
431 // (getCurrentWorkingDirectory) is a symlink./ We always want to the real
432 // file path (instead of the symlink path) for the C++ symbols.
433 //
434 // Consider the following example:
435 //
436 // src dir: /project/src/foo.h
437 // current working directory (symlink): /tmp/build -> /project/src/
438 //
439 // The file path of Symbol is "/project/src/foo.h" instead of
440 // "/tmp/build/foo.h"
441 if (const DirectoryEntry *Dir = SourceMgr.getFileManager().getDirectory(
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000442 llvm::sys::path::parent_path(FilePath))) {
443 llvm::SmallString<128> RealPath;
444 llvm::StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir);
445 llvm::sys::path::append(RealPath, DirName,
446 llvm::sys::path::filename(FilePath));
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000447 return RealPath.str().str();
Simon Marchi25f1f732018-08-10 22:27:53 +0000448 }
449
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000450 return FilePath.str().str();
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000451}
452
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +0000453TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M,
454 const LangOptions &L) {
455 TextEdit Result;
456 Result.range =
457 halfOpenToRange(M, Lexer::makeFileCharRange(FixIt.RemoveRange, M, L));
458 Result.newText = FixIt.CodeToInsert;
459 return Result;
460}
461
Haojian Wuaa3ed5a2019-01-25 15:14:03 +0000462bool isRangeConsecutive(const Range &Left, const Range &Right) {
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +0000463 return Left.end.line == Right.start.line &&
464 Left.end.character == Right.start.character;
465}
466
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000467FileDigest digest(llvm::StringRef Content) {
Sam McCall674d8a92019-07-08 11:33:17 +0000468 uint64_t Hash{llvm::xxHash64(Content)};
469 FileDigest Result;
470 for (unsigned I = 0; I < Result.size(); ++I) {
471 Result[I] = uint8_t(Hash);
472 Hash >>= 8;
473 }
474 return Result;
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000475}
476
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000477llvm::Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID) {
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000478 bool Invalid = false;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000479 llvm::StringRef Content = SM.getBufferData(FID, &Invalid);
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000480 if (Invalid)
481 return None;
482 return digest(Content);
483}
484
Eric Liudd662772019-01-28 14:01:55 +0000485format::FormatStyle getFormatStyleForFile(llvm::StringRef File,
486 llvm::StringRef Content,
487 llvm::vfs::FileSystem *FS) {
488 auto Style = format::getStyle(format::DefaultFormatStyle, File,
489 format::DefaultFallbackStyle, Content, FS);
490 if (!Style) {
491 log("getStyle() failed for file {0}: {1}. Fallback is LLVM style.", File,
492 Style.takeError());
493 Style = format::getLLVMStyle();
494 }
495 return *Style;
496}
497
Haojian Wu12e194c2019-02-06 15:24:50 +0000498llvm::Expected<tooling::Replacements>
499cleanupAndFormat(StringRef Code, const tooling::Replacements &Replaces,
500 const format::FormatStyle &Style) {
501 auto CleanReplaces = cleanupAroundReplacements(Code, Replaces, Style);
502 if (!CleanReplaces)
503 return CleanReplaces;
504 return formatReplacements(Code, std::move(*CleanReplaces), Style);
505}
506
Sam McCallc316b222019-04-26 07:45:49 +0000507template <typename Action>
508static void lex(llvm::StringRef Code, const format::FormatStyle &Style,
509 Action A) {
510 // FIXME: InMemoryFileAdapter crashes unless the buffer is null terminated!
511 std::string NullTerminatedCode = Code.str();
512 SourceManagerForFile FileSM("dummy.cpp", NullTerminatedCode);
Eric Liu00d99bd2019-04-11 09:36:36 +0000513 auto &SM = FileSM.get();
514 auto FID = SM.getMainFileID();
515 Lexer Lex(FID, SM.getBuffer(FID), SM, format::getFormattingLangOpts(Style));
516 Token Tok;
517
Sam McCallc316b222019-04-26 07:45:49 +0000518 while (!Lex.LexFromRawLexer(Tok))
519 A(Tok);
520}
521
522llvm::StringMap<unsigned> collectIdentifiers(llvm::StringRef Content,
523 const format::FormatStyle &Style) {
Eric Liu00d99bd2019-04-11 09:36:36 +0000524 llvm::StringMap<unsigned> Identifiers;
Sam McCallc316b222019-04-26 07:45:49 +0000525 lex(Content, Style, [&](const clang::Token &Tok) {
Eric Liu00d99bd2019-04-11 09:36:36 +0000526 switch (Tok.getKind()) {
527 case tok::identifier:
528 ++Identifiers[Tok.getIdentifierInfo()->getName()];
529 break;
530 case tok::raw_identifier:
531 ++Identifiers[Tok.getRawIdentifier()];
532 break;
533 default:
Sam McCallc316b222019-04-26 07:45:49 +0000534 break;
Eric Liu00d99bd2019-04-11 09:36:36 +0000535 }
Sam McCallc316b222019-04-26 07:45:49 +0000536 });
Eric Liu00d99bd2019-04-11 09:36:36 +0000537 return Identifiers;
538}
539
Sam McCallc316b222019-04-26 07:45:49 +0000540namespace {
541enum NamespaceEvent {
542 BeginNamespace, // namespace <ns> {. Payload is resolved <ns>.
543 EndNamespace, // } // namespace <ns>. Payload is resolved *outer* namespace.
544 UsingDirective // using namespace <ns>. Payload is unresolved <ns>.
545};
546// Scans C++ source code for constructs that change the visible namespaces.
547void parseNamespaceEvents(
548 llvm::StringRef Code, const format::FormatStyle &Style,
549 llvm::function_ref<void(NamespaceEvent, llvm::StringRef)> Callback) {
550
551 // Stack of enclosing namespaces, e.g. {"clang", "clangd"}
552 std::vector<std::string> Enclosing; // Contains e.g. "clang", "clangd"
553 // Stack counts open braces. true if the brace opened a namespace.
554 std::vector<bool> BraceStack;
555
556 enum {
557 Default,
558 Namespace, // just saw 'namespace'
559 NamespaceName, // just saw 'namespace' NSName
560 Using, // just saw 'using'
561 UsingNamespace, // just saw 'using namespace'
562 UsingNamespaceName, // just saw 'using namespace' NSName
563 } State = Default;
564 std::string NSName;
565
566 lex(Code, Style, [&](const clang::Token &Tok) {
567 switch(Tok.getKind()) {
568 case tok::raw_identifier:
569 // In raw mode, this could be a keyword or a name.
570 switch (State) {
571 case UsingNamespace:
572 case UsingNamespaceName:
573 NSName.append(Tok.getRawIdentifier());
574 State = UsingNamespaceName;
575 break;
576 case Namespace:
577 case NamespaceName:
578 NSName.append(Tok.getRawIdentifier());
579 State = NamespaceName;
580 break;
581 case Using:
582 State =
583 (Tok.getRawIdentifier() == "namespace") ? UsingNamespace : Default;
584 break;
585 case Default:
586 NSName.clear();
587 if (Tok.getRawIdentifier() == "namespace")
588 State = Namespace;
589 else if (Tok.getRawIdentifier() == "using")
590 State = Using;
591 break;
592 }
593 break;
594 case tok::coloncolon:
595 // This can come at the beginning or in the middle of a namespace name.
596 switch (State) {
597 case UsingNamespace:
598 case UsingNamespaceName:
599 NSName.append("::");
600 State = UsingNamespaceName;
601 break;
602 case NamespaceName:
603 NSName.append("::");
604 State = NamespaceName;
605 break;
606 case Namespace: // Not legal here.
607 case Using:
608 case Default:
609 State = Default;
610 break;
611 }
612 break;
613 case tok::l_brace:
614 // Record which { started a namespace, so we know when } ends one.
615 if (State == NamespaceName) {
616 // Parsed: namespace <name> {
617 BraceStack.push_back(true);
618 Enclosing.push_back(NSName);
619 Callback(BeginNamespace, llvm::join(Enclosing, "::"));
620 } else {
621 // This case includes anonymous namespaces (State = Namespace).
622 // For our purposes, they're not namespaces and we ignore them.
623 BraceStack.push_back(false);
624 }
625 State = Default;
626 break;
627 case tok::r_brace:
628 // If braces are unmatched, we're going to be confused, but don't crash.
629 if (!BraceStack.empty()) {
630 if (BraceStack.back()) {
631 // Parsed: } // namespace
632 Enclosing.pop_back();
633 Callback(EndNamespace, llvm::join(Enclosing, "::"));
634 }
635 BraceStack.pop_back();
636 }
637 break;
638 case tok::semi:
639 if (State == UsingNamespaceName)
640 // Parsed: using namespace <name> ;
641 Callback(UsingDirective, llvm::StringRef(NSName));
642 State = Default;
643 break;
644 default:
645 State = Default;
646 break;
647 }
648 });
649}
650
651// Returns the prefix namespaces of NS: {"" ... NS}.
652llvm::SmallVector<llvm::StringRef, 8> ancestorNamespaces(llvm::StringRef NS) {
653 llvm::SmallVector<llvm::StringRef, 8> Results;
654 Results.push_back(NS.take_front(0));
655 NS.split(Results, "::", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
656 for (llvm::StringRef &R : Results)
657 R = NS.take_front(R.end() - NS.begin());
658 return Results;
659}
660
661} // namespace
662
663std::vector<std::string> visibleNamespaces(llvm::StringRef Code,
664 const format::FormatStyle &Style) {
665 std::string Current;
666 // Map from namespace to (resolved) namespaces introduced via using directive.
667 llvm::StringMap<llvm::StringSet<>> UsingDirectives;
668
669 parseNamespaceEvents(Code, Style,
670 [&](NamespaceEvent Event, llvm::StringRef NS) {
671 switch (Event) {
672 case BeginNamespace:
673 case EndNamespace:
674 Current = NS;
675 break;
676 case UsingDirective:
677 if (NS.consume_front("::"))
678 UsingDirectives[Current].insert(NS);
679 else {
680 for (llvm::StringRef Enclosing :
681 ancestorNamespaces(Current)) {
682 if (Enclosing.empty())
683 UsingDirectives[Current].insert(NS);
684 else
685 UsingDirectives[Current].insert(
686 (Enclosing + "::" + NS).str());
687 }
688 }
689 break;
690 }
691 });
692
693 std::vector<std::string> Found;
694 for (llvm::StringRef Enclosing : ancestorNamespaces(Current)) {
695 Found.push_back(Enclosing);
696 auto It = UsingDirectives.find(Enclosing);
697 if (It != UsingDirectives.end())
698 for (const auto& Used : It->second)
699 Found.push_back(Used.getKey());
700 }
701
Sam McCallc316b222019-04-26 07:45:49 +0000702 llvm::sort(Found, [&](const std::string &LHS, const std::string &RHS) {
703 if (Current == RHS)
704 return false;
705 if (Current == LHS)
706 return true;
707 return LHS < RHS;
708 });
709 Found.erase(std::unique(Found.begin(), Found.end()), Found.end());
710 return Found;
711}
712
Sam McCall9fb22b22019-05-06 10:25:10 +0000713llvm::StringSet<> collectWords(llvm::StringRef Content) {
714 // We assume short words are not significant.
715 // We may want to consider other stopwords, e.g. language keywords.
716 // (A very naive implementation showed no benefit, but lexing might do better)
717 static constexpr int MinWordLength = 4;
718
719 std::vector<CharRole> Roles(Content.size());
720 calculateRoles(Content, Roles);
721
722 llvm::StringSet<> Result;
723 llvm::SmallString<256> Word;
724 auto Flush = [&] {
725 if (Word.size() >= MinWordLength) {
726 for (char &C : Word)
727 C = llvm::toLower(C);
728 Result.insert(Word);
729 }
730 Word.clear();
731 };
732 for (unsigned I = 0; I < Content.size(); ++I) {
733 switch (Roles[I]) {
734 case Head:
735 Flush();
736 LLVM_FALLTHROUGH;
737 case Tail:
738 Word.push_back(Content[I]);
739 break;
740 case Unknown:
741 case Separator:
742 Flush();
743 break;
744 }
745 }
746 Flush();
747
748 return Result;
749}
750
Haojian Wu9d34f452019-07-01 09:26:48 +0000751llvm::Optional<DefinedMacro> locateMacroAt(SourceLocation Loc,
752 Preprocessor &PP) {
753 const auto &SM = PP.getSourceManager();
754 const auto &LangOpts = PP.getLangOpts();
755 Token Result;
756 if (Lexer::getRawToken(SM.getSpellingLoc(Loc), Result, SM, LangOpts, false))
757 return None;
758 if (Result.is(tok::raw_identifier))
759 PP.LookUpIdentifierInfo(Result);
760 IdentifierInfo *IdentifierInfo = Result.getIdentifierInfo();
761 if (!IdentifierInfo || !IdentifierInfo->hadMacroDefinition())
762 return None;
763
764 std::pair<FileID, unsigned int> DecLoc = SM.getDecomposedExpansionLoc(Loc);
765 // Get the definition just before the searched location so that a macro
766 // referenced in a '#undef MACRO' can still be found.
767 SourceLocation BeforeSearchedLocation =
768 SM.getMacroArgExpandedLocation(SM.getLocForStartOfFile(DecLoc.first)
769 .getLocWithOffset(DecLoc.second - 1));
770 MacroDefinition MacroDef =
771 PP.getMacroDefinitionAtLoc(IdentifierInfo, BeforeSearchedLocation);
772 if (auto *MI = MacroDef.getMacroInfo())
773 return DefinedMacro{IdentifierInfo->getName(), MI};
774 return None;
775}
776
Sam McCallb536a2a2017-12-19 12:23:48 +0000777} // namespace clangd
778} // namespace clang