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