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