1 //===--- SourceCode.h - Manipulating source code as strings -----*- C++ -*-===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 #include "SourceCode.h"
9 
10 #include "Context.h"
11 #include "FuzzyMatch.h"
12 #include "Logger.h"
13 #include "Protocol.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/Basic/LangOptions.h"
16 #include "clang/Basic/SourceLocation.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "clang/Basic/TokenKinds.h"
19 #include "clang/Format/Format.h"
20 #include "clang/Lex/Lexer.h"
21 #include "clang/Lex/Preprocessor.h"
22 #include "llvm/ADT/None.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Errc.h"
27 #include "llvm/Support/Error.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/xxhash.h"
31 #include <algorithm>
32 
33 namespace clang {
34 namespace clangd {
35 
36 // 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.
42 template <typename Callback>
43 static bool iterateCodepoints(llvm::StringRef U8, const Callback &CB) {
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, starting with 11110xxx.
46   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.
55     size_t UTF8Length = llvm::countLeadingOnes(C);
56     // 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 
69 // 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.
73 static size_t measureUnits(llvm::StringRef U8, int Units, OffsetEncoding Enc,
74                            bool &Valid) {
75   Valid = Units >= 0;
76   if (Units <= 0)
77     return 0;
78   size_t Result = 0;
79   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   }
102   // Don't return an out-of-range index if we overran.
103   if (Result > U8.size()) {
104     Valid = false;
105     return U8.size();
106   }
107   return Result;
108 }
109 
110 Key<OffsetEncoding> kCurrentOffsetEncoding;
111 static OffsetEncoding lspEncoding() {
112   auto *Enc = Context::current().get(kCurrentOffsetEncoding);
113   return Enc ? *Enc : OffsetEncoding::UTF16;
114 }
115 
116 // Like most strings in clangd, the input is UTF-8 encoded.
117 size_t lspLength(llvm::StringRef Code) {
118   size_t Count = 0;
119   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   }
138   return Count;
139 }
140 
141 llvm::Expected<size_t> positionToOffset(llvm::StringRef Code, Position P,
142                                         bool AllowColumnsBeyondLineLength) {
143   if (P.line < 0)
144     return llvm::make_error<llvm::StringError>(
145         llvm::formatv("Line value can't be negative ({0})", P.line),
146         llvm::errc::invalid_argument);
147   if (P.character < 0)
148     return llvm::make_error<llvm::StringError>(
149         llvm::formatv("Character value can't be negative ({0})", P.character),
150         llvm::errc::invalid_argument);
151   size_t StartOfLine = 0;
152   for (int I = 0; I != P.line; ++I) {
153     size_t NextNL = Code.find('\n', StartOfLine);
154     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);
158     StartOfLine = NextNL + 1;
159   }
160   StringRef Line =
161       Code.substr(StartOfLine).take_until([](char C) { return C == '\n'; });
162 
163   // P.character may be in UTF-16, transcode if necessary.
164   bool Valid;
165   size_t ByteInLine = measureUnits(Line, P.character, lspEncoding(), Valid);
166   if (!Valid && !AllowColumnsBeyondLineLength)
167     return llvm::make_error<llvm::StringError>(
168         llvm::formatv("{0} offset {1} is invalid for line {2}", lspEncoding(),
169                       P.character, P.line),
170         llvm::errc::invalid_argument);
171   return StartOfLine + ByteInLine;
172 }
173 
174 Position offsetToPosition(llvm::StringRef Code, size_t Offset) {
175   Offset = std::min(Code.size(), Offset);
176   llvm::StringRef Before = Code.substr(0, Offset);
177   int Lines = Before.count('\n');
178   size_t PrevNL = Before.rfind('\n');
179   size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
180   Position Pos;
181   Pos.line = Lines;
182   Pos.character = lspLength(Before.substr(StartOfLine));
183   return Pos;
184 }
185 
186 Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc) {
187   // 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);
191   Position P;
192   P.line = static_cast<int>(SM.getLineNumber(FID, Offset)) - 1;
193   bool Invalid = false;
194   llvm::StringRef Code = SM.getBufferData(FID, &Invalid);
195   if (!Invalid) {
196     auto ColumnInBytes = SM.getColumnNumber(FID, Offset) - 1;
197     auto LineSoFar = Code.substr(Offset - ColumnInBytes, ColumnInBytes);
198     P.character = lspLength(LineSoFar);
199   }
200   return P;
201 }
202 
203 bool isSpelledInSource(SourceLocation Loc, const SourceManager &SM) {
204   if (Loc.isMacroID()) {
205     std::string PrintLoc = SM.getSpellingLoc(Loc).printToString(SM);
206     if (llvm::StringRef(PrintLoc).startswith("<scratch") ||
207         llvm::StringRef(PrintLoc).startswith("<command line>"))
208       return false;
209   }
210   return true;
211 }
212 
213 SourceLocation spellingLocIfSpelled(SourceLocation Loc,
214                                     const SourceManager &SM) {
215   if (!isSpelledInSource(Loc, SM))
216     // Use the expansion location as spelling location is not interesting.
217     return SM.getExpansionRange(Loc).getBegin();
218   return SM.getSpellingLoc(Loc);
219 }
220 
221 llvm::Optional<Range> getTokenRange(const SourceManager &SM,
222                                     const LangOptions &LangOpts,
223                                     SourceLocation TokLoc) {
224   if (!TokLoc.isValid())
225     return llvm::None;
226   SourceLocation End = Lexer::getLocForEndOfToken(TokLoc, 0, SM, LangOpts);
227   if (!End.isValid())
228     return llvm::None;
229   return halfOpenToRange(SM, CharSourceRange::getCharRange(TokLoc, End));
230 }
231 
232 bool isValidFileRange(const SourceManager &Mgr, SourceRange R) {
233   if (!R.getBegin().isValid() || !R.getEnd().isValid())
234     return false;
235 
236   FileID BeginFID;
237   size_t BeginOffset = 0;
238   std::tie(BeginFID, BeginOffset) = Mgr.getDecomposedLoc(R.getBegin());
239 
240   FileID EndFID;
241   size_t EndOffset = 0;
242   std::tie(EndFID, EndOffset) = Mgr.getDecomposedLoc(R.getEnd());
243 
244   return BeginFID.isValid() && BeginFID == EndFID && BeginOffset <= EndOffset;
245 }
246 
247 bool halfOpenRangeContains(const SourceManager &Mgr, SourceRange R,
248                            SourceLocation L) {
249   assert(isValidFileRange(Mgr, R));
250 
251   FileID BeginFID;
252   size_t BeginOffset = 0;
253   std::tie(BeginFID, BeginOffset) = Mgr.getDecomposedLoc(R.getBegin());
254   size_t EndOffset = Mgr.getFileOffset(R.getEnd());
255 
256   FileID LFid;
257   size_t LOffset;
258   std::tie(LFid, LOffset) = Mgr.getDecomposedLoc(L);
259   return BeginFID == LFid && BeginOffset <= LOffset && LOffset < EndOffset;
260 }
261 
262 bool halfOpenRangeTouches(const SourceManager &Mgr, SourceRange R,
263                           SourceLocation L) {
264   return L == R.getEnd() || halfOpenRangeContains(Mgr, R, L);
265 }
266 
267 SourceLocation includeHashLoc(FileID IncludedFile, const SourceManager &SM) {
268   assert(SM.getLocForEndOfFile(IncludedFile).isFileID());
269   FileID IncludingFile;
270   unsigned Offset;
271   std::tie(IncludingFile, Offset) =
272       SM.getDecomposedExpansionLoc(SM.getIncludeLoc(IncludedFile));
273   bool Invalid = false;
274   llvm::StringRef Buf = SM.getBufferData(IncludingFile, &Invalid);
275   if (Invalid)
276     return SourceLocation();
277   // Now buf is "...\n#include <foo>\n..."
278   // and Offset points here:   ^
279   // Rewind to the preceding # on the line.
280   assert(Offset < Buf.size());
281   for (;; --Offset) {
282     if (Buf[Offset] == '#')
283       return SM.getComposedLoc(IncludingFile, Offset);
284     if (Buf[Offset] == '\n' || Offset == 0) // no hash, what's going on?
285       return SourceLocation();
286   }
287 }
288 
289 
290 static unsigned getTokenLengthAtLoc(SourceLocation Loc, const SourceManager &SM,
291                                     const LangOptions &LangOpts) {
292   Token TheTok;
293   if (Lexer::getRawToken(Loc, TheTok, SM, LangOpts))
294     return 0;
295   // FIXME: Here we check whether the token at the location is a greatergreater
296   // (>>) token and consider it as a single greater (>). This is to get it
297   // working for templates but it isn't correct for the right shift operator. We
298   // can avoid this by using half open char ranges in getFileRange() but getting
299   // token ending is not well supported in macroIDs.
300   if (TheTok.is(tok::greatergreater))
301     return 1;
302   return TheTok.getLength();
303 }
304 
305 // Returns location of the last character of the token at a given loc
306 static SourceLocation getLocForTokenEnd(SourceLocation BeginLoc,
307                                         const SourceManager &SM,
308                                         const LangOptions &LangOpts) {
309   unsigned Len = getTokenLengthAtLoc(BeginLoc, SM, LangOpts);
310   return BeginLoc.getLocWithOffset(Len ? Len - 1 : 0);
311 }
312 
313 // Returns location of the starting of the token at a given EndLoc
314 static SourceLocation getLocForTokenBegin(SourceLocation EndLoc,
315                                           const SourceManager &SM,
316                                           const LangOptions &LangOpts) {
317   return EndLoc.getLocWithOffset(
318       -(signed)getTokenLengthAtLoc(EndLoc, SM, LangOpts));
319 }
320 
321 // Converts a char source range to a token range.
322 static SourceRange toTokenRange(CharSourceRange Range, const SourceManager &SM,
323                                 const LangOptions &LangOpts) {
324   if (!Range.isTokenRange())
325     Range.setEnd(getLocForTokenBegin(Range.getEnd(), SM, LangOpts));
326   return Range.getAsRange();
327 }
328 // Returns the union of two token ranges.
329 // To find the maximum of the Ends of the ranges, we compare the location of the
330 // last character of the token.
331 static SourceRange unionTokenRange(SourceRange R1, SourceRange R2,
332                                    const SourceManager &SM,
333                                    const LangOptions &LangOpts) {
334   SourceLocation Begin =
335       SM.isBeforeInTranslationUnit(R1.getBegin(), R2.getBegin())
336           ? R1.getBegin()
337           : R2.getBegin();
338   SourceLocation End =
339       SM.isBeforeInTranslationUnit(getLocForTokenEnd(R1.getEnd(), SM, LangOpts),
340                                    getLocForTokenEnd(R2.getEnd(), SM, LangOpts))
341           ? R2.getEnd()
342           : R1.getEnd();
343   return SourceRange(Begin, End);
344 }
345 
346 // Given a range whose endpoints may be in different expansions or files,
347 // tries to find a range within a common file by following up the expansion and
348 // include location in each.
349 static SourceRange rangeInCommonFile(SourceRange R, const SourceManager &SM,
350                                      const LangOptions &LangOpts) {
351   // Fast path for most common cases.
352   if (SM.isWrittenInSameFile(R.getBegin(), R.getEnd()))
353     return R;
354   // Record the stack of expansion locations for the beginning, keyed by FileID.
355   llvm::DenseMap<FileID, SourceLocation> BeginExpansions;
356   for (SourceLocation Begin = R.getBegin(); Begin.isValid();
357        Begin = Begin.isFileID()
358                    ? includeHashLoc(SM.getFileID(Begin), SM)
359                    : SM.getImmediateExpansionRange(Begin).getBegin()) {
360     BeginExpansions[SM.getFileID(Begin)] = Begin;
361   }
362   // Move up the stack of expansion locations for the end until we find the
363   // location in BeginExpansions with that has the same file id.
364   for (SourceLocation End = R.getEnd(); End.isValid();
365        End = End.isFileID() ? includeHashLoc(SM.getFileID(End), SM)
366                             : toTokenRange(SM.getImmediateExpansionRange(End),
367                                            SM, LangOpts)
368                                   .getEnd()) {
369     auto It = BeginExpansions.find(SM.getFileID(End));
370     if (It != BeginExpansions.end()) {
371       if (SM.getFileOffset(It->second) > SM.getFileOffset(End))
372         return SourceLocation();
373       return {It->second, End};
374     }
375   }
376   return SourceRange();
377 }
378 
379 // Find an expansion range (not necessarily immediate) the ends of which are in
380 // the same file id.
381 static SourceRange
382 getExpansionTokenRangeInSameFile(SourceLocation Loc, const SourceManager &SM,
383                                  const LangOptions &LangOpts) {
384   return rangeInCommonFile(
385       toTokenRange(SM.getImmediateExpansionRange(Loc), SM, LangOpts), SM,
386       LangOpts);
387 }
388 
389 // Returns the file range for a given Location as a Token Range
390 // This is quite similar to getFileLoc in SourceManager as both use
391 // getImmediateExpansionRange and getImmediateSpellingLoc (for macro IDs).
392 // However:
393 // - We want to maintain the full range information as we move from one file to
394 //   the next. getFileLoc only uses the BeginLoc of getImmediateExpansionRange.
395 // - We want to split '>>' tokens as the lexer parses the '>>' in nested
396 //   template instantiations as a '>>' instead of two '>'s.
397 // There is also getExpansionRange but it simply calls
398 // getImmediateExpansionRange on the begin and ends separately which is wrong.
399 static SourceRange getTokenFileRange(SourceLocation Loc,
400                                      const SourceManager &SM,
401                                      const LangOptions &LangOpts) {
402   SourceRange FileRange = Loc;
403   while (!FileRange.getBegin().isFileID()) {
404     if (SM.isMacroArgExpansion(FileRange.getBegin())) {
405       FileRange = unionTokenRange(
406           SM.getImmediateSpellingLoc(FileRange.getBegin()),
407           SM.getImmediateSpellingLoc(FileRange.getEnd()), SM, LangOpts);
408       assert(SM.isWrittenInSameFile(FileRange.getBegin(), FileRange.getEnd()));
409     } else {
410       SourceRange ExpansionRangeForBegin =
411           getExpansionTokenRangeInSameFile(FileRange.getBegin(), SM, LangOpts);
412       SourceRange ExpansionRangeForEnd =
413           getExpansionTokenRangeInSameFile(FileRange.getEnd(), SM, LangOpts);
414       if (ExpansionRangeForBegin.isInvalid() ||
415           ExpansionRangeForEnd.isInvalid())
416         return SourceRange();
417       assert(SM.isWrittenInSameFile(ExpansionRangeForBegin.getBegin(),
418                                     ExpansionRangeForEnd.getBegin()) &&
419              "Both Expansion ranges should be in same file.");
420       FileRange = unionTokenRange(ExpansionRangeForBegin, ExpansionRangeForEnd,
421                                   SM, LangOpts);
422     }
423   }
424   return FileRange;
425 }
426 
427 bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM) {
428   return Loc.isValid() && SM.isWrittenInMainFile(SM.getExpansionLoc(Loc));
429 }
430 
431 llvm::Optional<SourceRange> toHalfOpenFileRange(const SourceManager &SM,
432                                                 const LangOptions &LangOpts,
433                                                 SourceRange R) {
434   SourceRange R1 = getTokenFileRange(R.getBegin(), SM, LangOpts);
435   if (!isValidFileRange(SM, R1))
436     return llvm::None;
437 
438   SourceRange R2 = getTokenFileRange(R.getEnd(), SM, LangOpts);
439   if (!isValidFileRange(SM, R2))
440     return llvm::None;
441 
442   SourceRange Result =
443       rangeInCommonFile(unionTokenRange(R1, R2, SM, LangOpts), SM, LangOpts);
444   unsigned TokLen = getTokenLengthAtLoc(Result.getEnd(), SM, LangOpts);
445   // Convert from closed token range to half-open (char) range
446   Result.setEnd(Result.getEnd().getLocWithOffset(TokLen));
447   if (!isValidFileRange(SM, Result))
448     return llvm::None;
449 
450   return Result;
451 }
452 
453 llvm::StringRef toSourceCode(const SourceManager &SM, SourceRange R) {
454   assert(isValidFileRange(SM, R));
455   bool Invalid = false;
456   auto *Buf = SM.getBuffer(SM.getFileID(R.getBegin()), &Invalid);
457   assert(!Invalid);
458 
459   size_t BeginOffset = SM.getFileOffset(R.getBegin());
460   size_t EndOffset = SM.getFileOffset(R.getEnd());
461   return Buf->getBuffer().substr(BeginOffset, EndOffset - BeginOffset);
462 }
463 
464 llvm::Expected<SourceLocation> sourceLocationInMainFile(const SourceManager &SM,
465                                                         Position P) {
466   llvm::StringRef Code = SM.getBuffer(SM.getMainFileID())->getBuffer();
467   auto Offset =
468       positionToOffset(Code, P, /*AllowColumnBeyondLineLength=*/false);
469   if (!Offset)
470     return Offset.takeError();
471   return SM.getLocForStartOfFile(SM.getMainFileID()).getLocWithOffset(*Offset);
472 }
473 
474 Range halfOpenToRange(const SourceManager &SM, CharSourceRange R) {
475   // Clang is 1-based, LSP uses 0-based indexes.
476   Position Begin = sourceLocToPosition(SM, R.getBegin());
477   Position End = sourceLocToPosition(SM, R.getEnd());
478 
479   return {Begin, End};
480 }
481 
482 std::pair<size_t, size_t> offsetToClangLineColumn(llvm::StringRef Code,
483                                                   size_t Offset) {
484   Offset = std::min(Code.size(), Offset);
485   llvm::StringRef Before = Code.substr(0, Offset);
486   int Lines = Before.count('\n');
487   size_t PrevNL = Before.rfind('\n');
488   size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
489   return {Lines + 1, Offset - StartOfLine + 1};
490 }
491 
492 std::pair<StringRef, StringRef> splitQualifiedName(StringRef QName) {
493   size_t Pos = QName.rfind("::");
494   if (Pos == llvm::StringRef::npos)
495     return {llvm::StringRef(), QName};
496   return {QName.substr(0, Pos + 2), QName.substr(Pos + 2)};
497 }
498 
499 TextEdit replacementToEdit(llvm::StringRef Code,
500                            const tooling::Replacement &R) {
501   Range ReplacementRange = {
502       offsetToPosition(Code, R.getOffset()),
503       offsetToPosition(Code, R.getOffset() + R.getLength())};
504   return {ReplacementRange, R.getReplacementText()};
505 }
506 
507 std::vector<TextEdit> replacementsToEdits(llvm::StringRef Code,
508                                           const tooling::Replacements &Repls) {
509   std::vector<TextEdit> Edits;
510   for (const auto &R : Repls)
511     Edits.push_back(replacementToEdit(Code, R));
512   return Edits;
513 }
514 
515 llvm::Optional<std::string> getCanonicalPath(const FileEntry *F,
516                                              const SourceManager &SourceMgr) {
517   if (!F)
518     return None;
519 
520   llvm::SmallString<128> FilePath = F->getName();
521   if (!llvm::sys::path::is_absolute(FilePath)) {
522     if (auto EC =
523             SourceMgr.getFileManager().getVirtualFileSystem().makeAbsolute(
524                 FilePath)) {
525       elog("Could not turn relative path '{0}' to absolute: {1}", FilePath,
526            EC.message());
527       return None;
528     }
529   }
530 
531   // Handle the symbolic link path case where the current working directory
532   // (getCurrentWorkingDirectory) is a symlink./ We always want to the real
533   // file path (instead of the symlink path) for the  C++ symbols.
534   //
535   // Consider the following example:
536   //
537   //   src dir: /project/src/foo.h
538   //   current working directory (symlink): /tmp/build -> /project/src/
539   //
540   //  The file path of Symbol is "/project/src/foo.h" instead of
541   //  "/tmp/build/foo.h"
542   if (auto Dir = SourceMgr.getFileManager().getDirectory(
543           llvm::sys::path::parent_path(FilePath))) {
544     llvm::SmallString<128> RealPath;
545     llvm::StringRef DirName = SourceMgr.getFileManager().getCanonicalName(*Dir);
546     llvm::sys::path::append(RealPath, DirName,
547                             llvm::sys::path::filename(FilePath));
548     return RealPath.str().str();
549   }
550 
551   return FilePath.str().str();
552 }
553 
554 TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M,
555                     const LangOptions &L) {
556   TextEdit Result;
557   Result.range =
558       halfOpenToRange(M, Lexer::makeFileCharRange(FixIt.RemoveRange, M, L));
559   Result.newText = FixIt.CodeToInsert;
560   return Result;
561 }
562 
563 bool isRangeConsecutive(const Range &Left, const Range &Right) {
564   return Left.end.line == Right.start.line &&
565          Left.end.character == Right.start.character;
566 }
567 
568 FileDigest digest(llvm::StringRef Content) {
569   uint64_t Hash{llvm::xxHash64(Content)};
570   FileDigest Result;
571   for (unsigned I = 0; I < Result.size(); ++I) {
572     Result[I] = uint8_t(Hash);
573     Hash >>= 8;
574   }
575   return Result;
576 }
577 
578 llvm::Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID) {
579   bool Invalid = false;
580   llvm::StringRef Content = SM.getBufferData(FID, &Invalid);
581   if (Invalid)
582     return None;
583   return digest(Content);
584 }
585 
586 format::FormatStyle getFormatStyleForFile(llvm::StringRef File,
587                                           llvm::StringRef Content,
588                                           llvm::vfs::FileSystem *FS) {
589   auto Style = format::getStyle(format::DefaultFormatStyle, File,
590                                 format::DefaultFallbackStyle, Content, FS);
591   if (!Style) {
592     log("getStyle() failed for file {0}: {1}. Fallback is LLVM style.", File,
593         Style.takeError());
594     Style = format::getLLVMStyle();
595   }
596   return *Style;
597 }
598 
599 llvm::Expected<tooling::Replacements>
600 cleanupAndFormat(StringRef Code, const tooling::Replacements &Replaces,
601                  const format::FormatStyle &Style) {
602   auto CleanReplaces = cleanupAroundReplacements(Code, Replaces, Style);
603   if (!CleanReplaces)
604     return CleanReplaces;
605   return formatReplacements(Code, std::move(*CleanReplaces), Style);
606 }
607 
608 template <typename Action>
609 static void lex(llvm::StringRef Code, const format::FormatStyle &Style,
610                 Action A) {
611   // FIXME: InMemoryFileAdapter crashes unless the buffer is null terminated!
612   std::string NullTerminatedCode = Code.str();
613   SourceManagerForFile FileSM("dummy.cpp", NullTerminatedCode);
614   auto &SM = FileSM.get();
615   auto FID = SM.getMainFileID();
616   Lexer Lex(FID, SM.getBuffer(FID), SM, format::getFormattingLangOpts(Style));
617   Token Tok;
618 
619   while (!Lex.LexFromRawLexer(Tok))
620     A(Tok);
621 }
622 
623 llvm::StringMap<unsigned> collectIdentifiers(llvm::StringRef Content,
624                                              const format::FormatStyle &Style) {
625   llvm::StringMap<unsigned> Identifiers;
626   lex(Content, Style, [&](const clang::Token &Tok) {
627     switch (Tok.getKind()) {
628     case tok::identifier:
629       ++Identifiers[Tok.getIdentifierInfo()->getName()];
630       break;
631     case tok::raw_identifier:
632       ++Identifiers[Tok.getRawIdentifier()];
633       break;
634     default:
635       break;
636     }
637   });
638   return Identifiers;
639 }
640 
641 namespace {
642 enum NamespaceEvent {
643   BeginNamespace, // namespace <ns> {.     Payload is resolved <ns>.
644   EndNamespace,   // } // namespace <ns>.  Payload is resolved *outer* namespace.
645   UsingDirective  // using namespace <ns>. Payload is unresolved <ns>.
646 };
647 // Scans C++ source code for constructs that change the visible namespaces.
648 void parseNamespaceEvents(
649     llvm::StringRef Code, const format::FormatStyle &Style,
650     llvm::function_ref<void(NamespaceEvent, llvm::StringRef)> Callback) {
651 
652   // Stack of enclosing namespaces, e.g. {"clang", "clangd"}
653   std::vector<std::string> Enclosing; // Contains e.g. "clang", "clangd"
654   // Stack counts open braces. true if the brace opened a namespace.
655   std::vector<bool> BraceStack;
656 
657   enum {
658     Default,
659     Namespace,          // just saw 'namespace'
660     NamespaceName,      // just saw 'namespace' NSName
661     Using,              // just saw 'using'
662     UsingNamespace,     // just saw 'using namespace'
663     UsingNamespaceName, // just saw 'using namespace' NSName
664   } State = Default;
665   std::string NSName;
666 
667   lex(Code, Style, [&](const clang::Token &Tok) {
668     switch(Tok.getKind()) {
669     case tok::raw_identifier:
670       // In raw mode, this could be a keyword or a name.
671       switch (State) {
672       case UsingNamespace:
673       case UsingNamespaceName:
674         NSName.append(Tok.getRawIdentifier());
675         State = UsingNamespaceName;
676         break;
677       case Namespace:
678       case NamespaceName:
679         NSName.append(Tok.getRawIdentifier());
680         State = NamespaceName;
681         break;
682       case Using:
683         State =
684             (Tok.getRawIdentifier() == "namespace") ? UsingNamespace : Default;
685         break;
686       case Default:
687         NSName.clear();
688         if (Tok.getRawIdentifier() == "namespace")
689           State = Namespace;
690         else if (Tok.getRawIdentifier() == "using")
691           State = Using;
692         break;
693       }
694       break;
695     case tok::coloncolon:
696       // This can come at the beginning or in the middle of a namespace name.
697       switch (State) {
698       case UsingNamespace:
699       case UsingNamespaceName:
700         NSName.append("::");
701         State = UsingNamespaceName;
702         break;
703       case NamespaceName:
704         NSName.append("::");
705         State = NamespaceName;
706         break;
707       case Namespace: // Not legal here.
708       case Using:
709       case Default:
710         State = Default;
711         break;
712       }
713       break;
714     case tok::l_brace:
715       // Record which { started a namespace, so we know when } ends one.
716       if (State == NamespaceName) {
717         // Parsed: namespace <name> {
718         BraceStack.push_back(true);
719         Enclosing.push_back(NSName);
720         Callback(BeginNamespace, llvm::join(Enclosing, "::"));
721       } else {
722         // This case includes anonymous namespaces (State = Namespace).
723         // For our purposes, they're not namespaces and we ignore them.
724         BraceStack.push_back(false);
725       }
726       State = Default;
727       break;
728     case tok::r_brace:
729       // If braces are unmatched, we're going to be confused, but don't crash.
730       if (!BraceStack.empty()) {
731         if (BraceStack.back()) {
732           // Parsed: } // namespace
733           Enclosing.pop_back();
734           Callback(EndNamespace, llvm::join(Enclosing, "::"));
735         }
736         BraceStack.pop_back();
737       }
738       break;
739     case tok::semi:
740       if (State == UsingNamespaceName)
741         // Parsed: using namespace <name> ;
742         Callback(UsingDirective, llvm::StringRef(NSName));
743       State = Default;
744       break;
745     default:
746       State = Default;
747       break;
748     }
749   });
750 }
751 
752 // Returns the prefix namespaces of NS: {"" ... NS}.
753 llvm::SmallVector<llvm::StringRef, 8> ancestorNamespaces(llvm::StringRef NS) {
754   llvm::SmallVector<llvm::StringRef, 8> Results;
755   Results.push_back(NS.take_front(0));
756   NS.split(Results, "::", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
757   for (llvm::StringRef &R : Results)
758     R = NS.take_front(R.end() - NS.begin());
759   return Results;
760 }
761 
762 } // namespace
763 
764 std::vector<std::string> visibleNamespaces(llvm::StringRef Code,
765                                            const format::FormatStyle &Style) {
766   std::string Current;
767   // Map from namespace to (resolved) namespaces introduced via using directive.
768   llvm::StringMap<llvm::StringSet<>> UsingDirectives;
769 
770   parseNamespaceEvents(Code, Style,
771                        [&](NamespaceEvent Event, llvm::StringRef NS) {
772                          switch (Event) {
773                          case BeginNamespace:
774                          case EndNamespace:
775                            Current = NS;
776                            break;
777                          case UsingDirective:
778                            if (NS.consume_front("::"))
779                              UsingDirectives[Current].insert(NS);
780                            else {
781                              for (llvm::StringRef Enclosing :
782                                   ancestorNamespaces(Current)) {
783                                if (Enclosing.empty())
784                                  UsingDirectives[Current].insert(NS);
785                                else
786                                  UsingDirectives[Current].insert(
787                                      (Enclosing + "::" + NS).str());
788                              }
789                            }
790                            break;
791                          }
792                        });
793 
794   std::vector<std::string> Found;
795   for (llvm::StringRef Enclosing : ancestorNamespaces(Current)) {
796     Found.push_back(Enclosing);
797     auto It = UsingDirectives.find(Enclosing);
798     if (It != UsingDirectives.end())
799       for (const auto& Used : It->second)
800         Found.push_back(Used.getKey());
801   }
802 
803   llvm::sort(Found, [&](const std::string &LHS, const std::string &RHS) {
804     if (Current == RHS)
805       return false;
806     if (Current == LHS)
807       return true;
808     return LHS < RHS;
809   });
810   Found.erase(std::unique(Found.begin(), Found.end()), Found.end());
811   return Found;
812 }
813 
814 llvm::StringSet<> collectWords(llvm::StringRef Content) {
815   // We assume short words are not significant.
816   // We may want to consider other stopwords, e.g. language keywords.
817   // (A very naive implementation showed no benefit, but lexing might do better)
818   static constexpr int MinWordLength = 4;
819 
820   std::vector<CharRole> Roles(Content.size());
821   calculateRoles(Content, Roles);
822 
823   llvm::StringSet<> Result;
824   llvm::SmallString<256> Word;
825   auto Flush = [&] {
826     if (Word.size() >= MinWordLength) {
827       for (char &C : Word)
828         C = llvm::toLower(C);
829       Result.insert(Word);
830     }
831     Word.clear();
832   };
833   for (unsigned I = 0; I < Content.size(); ++I) {
834     switch (Roles[I]) {
835     case Head:
836       Flush();
837       LLVM_FALLTHROUGH;
838     case Tail:
839       Word.push_back(Content[I]);
840       break;
841     case Unknown:
842     case Separator:
843       Flush();
844       break;
845     }
846   }
847   Flush();
848 
849   return Result;
850 }
851 
852 llvm::Optional<DefinedMacro> locateMacroAt(SourceLocation Loc,
853                                            Preprocessor &PP) {
854   const auto &SM = PP.getSourceManager();
855   const auto &LangOpts = PP.getLangOpts();
856   Token Result;
857   if (Lexer::getRawToken(SM.getSpellingLoc(Loc), Result, SM, LangOpts, false))
858     return None;
859   if (Result.is(tok::raw_identifier))
860     PP.LookUpIdentifierInfo(Result);
861   IdentifierInfo *IdentifierInfo = Result.getIdentifierInfo();
862   if (!IdentifierInfo || !IdentifierInfo->hadMacroDefinition())
863     return None;
864 
865   std::pair<FileID, unsigned int> DecLoc = SM.getDecomposedExpansionLoc(Loc);
866   // Get the definition just before the searched location so that a macro
867   // referenced in a '#undef MACRO' can still be found.
868   SourceLocation BeforeSearchedLocation =
869       SM.getMacroArgExpandedLocation(SM.getLocForStartOfFile(DecLoc.first)
870                                          .getLocWithOffset(DecLoc.second - 1));
871   MacroDefinition MacroDef =
872       PP.getMacroDefinitionAtLoc(IdentifierInfo, BeforeSearchedLocation);
873   if (auto *MI = MacroDef.getMacroInfo())
874     return DefinedMacro{IdentifierInfo->getName(), MI};
875   return None;
876 }
877 
878 } // namespace clangd
879 } // namespace clang
880