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 static unsigned getTokenLengthAtLoc(SourceLocation Loc, const SourceManager &SM,
268                                     const LangOptions &LangOpts) {
269   Token TheTok;
270   if (Lexer::getRawToken(Loc, TheTok, SM, LangOpts))
271     return 0;
272   // FIXME: Here we check whether the token at the location is a greatergreater
273   // (>>) token and consider it as a single greater (>). This is to get it
274   // working for templates but it isn't correct for the right shift operator. We
275   // can avoid this by using half open char ranges in getFileRange() but getting
276   // token ending is not well supported in macroIDs.
277   if (TheTok.is(tok::greatergreater))
278     return 1;
279   return TheTok.getLength();
280 }
281 
282 // Returns location of the last character of the token at a given loc
283 static SourceLocation getLocForTokenEnd(SourceLocation BeginLoc,
284                                         const SourceManager &SM,
285                                         const LangOptions &LangOpts) {
286   unsigned Len = getTokenLengthAtLoc(BeginLoc, SM, LangOpts);
287   return BeginLoc.getLocWithOffset(Len ? Len - 1 : 0);
288 }
289 
290 // Returns location of the starting of the token at a given EndLoc
291 static SourceLocation getLocForTokenBegin(SourceLocation EndLoc,
292                                           const SourceManager &SM,
293                                           const LangOptions &LangOpts) {
294   return EndLoc.getLocWithOffset(
295       -(signed)getTokenLengthAtLoc(EndLoc, SM, LangOpts));
296 }
297 
298 // Converts a char source range to a token range.
299 static SourceRange toTokenRange(CharSourceRange Range, const SourceManager &SM,
300                                 const LangOptions &LangOpts) {
301   if (!Range.isTokenRange())
302     Range.setEnd(getLocForTokenBegin(Range.getEnd(), SM, LangOpts));
303   return Range.getAsRange();
304 }
305 // Returns the union of two token ranges.
306 // To find the maximum of the Ends of the ranges, we compare the location of the
307 // last character of the token.
308 static SourceRange unionTokenRange(SourceRange R1, SourceRange R2,
309                                    const SourceManager &SM,
310                                    const LangOptions &LangOpts) {
311   SourceLocation E1 = getLocForTokenEnd(R1.getEnd(), SM, LangOpts);
312   SourceLocation E2 = getLocForTokenEnd(R2.getEnd(), SM, LangOpts);
313   return SourceRange(std::min(R1.getBegin(), R2.getBegin()),
314                      E1 < E2 ? R2.getEnd() : R1.getEnd());
315 }
316 
317 // Check if two locations have the same file id.
318 static bool inSameFile(SourceLocation Loc1, SourceLocation Loc2,
319                        const SourceManager &SM) {
320   return SM.getFileID(Loc1) == SM.getFileID(Loc2);
321 }
322 
323 // Find an expansion range (not necessarily immediate) the ends of which are in
324 // the same file id.
325 static SourceRange
326 getExpansionTokenRangeInSameFile(SourceLocation Loc, const SourceManager &SM,
327                                  const LangOptions &LangOpts) {
328   SourceRange ExpansionRange =
329       toTokenRange(SM.getImmediateExpansionRange(Loc), SM, LangOpts);
330   // Fast path for most common cases.
331   if (inSameFile(ExpansionRange.getBegin(), ExpansionRange.getEnd(), SM))
332     return ExpansionRange;
333   // Record the stack of expansion locations for the beginning, keyed by FileID.
334   llvm::DenseMap<FileID, SourceLocation> BeginExpansions;
335   for (SourceLocation Begin = ExpansionRange.getBegin(); Begin.isValid();
336        Begin = Begin.isFileID()
337                    ? SourceLocation()
338                    : SM.getImmediateExpansionRange(Begin).getBegin()) {
339     BeginExpansions[SM.getFileID(Begin)] = Begin;
340   }
341   // Move up the stack of expansion locations for the end until we find the
342   // location in BeginExpansions with that has the same file id.
343   for (SourceLocation End = ExpansionRange.getEnd(); End.isValid();
344        End = End.isFileID() ? SourceLocation()
345                             : toTokenRange(SM.getImmediateExpansionRange(End),
346                                            SM, LangOpts)
347                                   .getEnd()) {
348     auto It = BeginExpansions.find(SM.getFileID(End));
349     if (It != BeginExpansions.end())
350       return {It->second, End};
351   }
352   llvm_unreachable(
353       "We should able to find a common ancestor in the expansion tree.");
354 }
355 // Returns the file range for a given Location as a Token Range
356 // This is quite similar to getFileLoc in SourceManager as both use
357 // getImmediateExpansionRange and getImmediateSpellingLoc (for macro IDs).
358 // However:
359 // - We want to maintain the full range information as we move from one file to
360 //   the next. getFileLoc only uses the BeginLoc of getImmediateExpansionRange.
361 // - We want to split '>>' tokens as the lexer parses the '>>' in nested
362 //   template instantiations as a '>>' instead of two '>'s.
363 // There is also getExpansionRange but it simply calls
364 // getImmediateExpansionRange on the begin and ends separately which is wrong.
365 static SourceRange getTokenFileRange(SourceLocation Loc,
366                                      const SourceManager &SM,
367                                      const LangOptions &LangOpts) {
368   SourceRange FileRange = Loc;
369   while (!FileRange.getBegin().isFileID()) {
370     if (SM.isMacroArgExpansion(FileRange.getBegin())) {
371       FileRange = unionTokenRange(
372           SM.getImmediateSpellingLoc(FileRange.getBegin()),
373           SM.getImmediateSpellingLoc(FileRange.getEnd()), SM, LangOpts);
374       assert(inSameFile(FileRange.getBegin(), FileRange.getEnd(), SM));
375     } else {
376       SourceRange ExpansionRangeForBegin =
377           getExpansionTokenRangeInSameFile(FileRange.getBegin(), SM, LangOpts);
378       SourceRange ExpansionRangeForEnd =
379           getExpansionTokenRangeInSameFile(FileRange.getEnd(), SM, LangOpts);
380       assert(inSameFile(ExpansionRangeForBegin.getBegin(),
381                         ExpansionRangeForEnd.getBegin(), SM) &&
382              "Both Expansion ranges should be in same file.");
383       FileRange = unionTokenRange(ExpansionRangeForBegin, ExpansionRangeForEnd,
384                                   SM, LangOpts);
385     }
386   }
387   return FileRange;
388 }
389 
390 bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM) {
391   return Loc.isValid() && SM.isWrittenInMainFile(SM.getExpansionLoc(Loc));
392 }
393 
394 llvm::Optional<SourceRange> toHalfOpenFileRange(const SourceManager &SM,
395                                                 const LangOptions &LangOpts,
396                                                 SourceRange R) {
397   SourceRange R1 = getTokenFileRange(R.getBegin(), SM, LangOpts);
398   if (!isValidFileRange(SM, R1))
399     return llvm::None;
400 
401   SourceRange R2 = getTokenFileRange(R.getEnd(), SM, LangOpts);
402   if (!isValidFileRange(SM, R2))
403     return llvm::None;
404 
405   SourceRange Result = unionTokenRange(R1, R2, SM, LangOpts);
406   unsigned TokLen = getTokenLengthAtLoc(Result.getEnd(), SM, LangOpts);
407   // Convert from closed token range to half-open (char) range
408   Result.setEnd(Result.getEnd().getLocWithOffset(TokLen));
409   if (!isValidFileRange(SM, Result))
410     return llvm::None;
411 
412   return Result;
413 }
414 
415 llvm::StringRef toSourceCode(const SourceManager &SM, SourceRange R) {
416   assert(isValidFileRange(SM, R));
417   bool Invalid = false;
418   auto *Buf = SM.getBuffer(SM.getFileID(R.getBegin()), &Invalid);
419   assert(!Invalid);
420 
421   size_t BeginOffset = SM.getFileOffset(R.getBegin());
422   size_t EndOffset = SM.getFileOffset(R.getEnd());
423   return Buf->getBuffer().substr(BeginOffset, EndOffset - BeginOffset);
424 }
425 
426 llvm::Expected<SourceLocation> sourceLocationInMainFile(const SourceManager &SM,
427                                                         Position P) {
428   llvm::StringRef Code = SM.getBuffer(SM.getMainFileID())->getBuffer();
429   auto Offset =
430       positionToOffset(Code, P, /*AllowColumnBeyondLineLength=*/false);
431   if (!Offset)
432     return Offset.takeError();
433   return SM.getLocForStartOfFile(SM.getMainFileID()).getLocWithOffset(*Offset);
434 }
435 
436 Range halfOpenToRange(const SourceManager &SM, CharSourceRange R) {
437   // Clang is 1-based, LSP uses 0-based indexes.
438   Position Begin = sourceLocToPosition(SM, R.getBegin());
439   Position End = sourceLocToPosition(SM, R.getEnd());
440 
441   return {Begin, End};
442 }
443 
444 std::pair<size_t, size_t> offsetToClangLineColumn(llvm::StringRef Code,
445                                                   size_t Offset) {
446   Offset = std::min(Code.size(), Offset);
447   llvm::StringRef Before = Code.substr(0, Offset);
448   int Lines = Before.count('\n');
449   size_t PrevNL = Before.rfind('\n');
450   size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
451   return {Lines + 1, Offset - StartOfLine + 1};
452 }
453 
454 std::pair<StringRef, StringRef> splitQualifiedName(StringRef QName) {
455   size_t Pos = QName.rfind("::");
456   if (Pos == llvm::StringRef::npos)
457     return {llvm::StringRef(), QName};
458   return {QName.substr(0, Pos + 2), QName.substr(Pos + 2)};
459 }
460 
461 TextEdit replacementToEdit(llvm::StringRef Code,
462                            const tooling::Replacement &R) {
463   Range ReplacementRange = {
464       offsetToPosition(Code, R.getOffset()),
465       offsetToPosition(Code, R.getOffset() + R.getLength())};
466   return {ReplacementRange, R.getReplacementText()};
467 }
468 
469 std::vector<TextEdit> replacementsToEdits(llvm::StringRef Code,
470                                           const tooling::Replacements &Repls) {
471   std::vector<TextEdit> Edits;
472   for (const auto &R : Repls)
473     Edits.push_back(replacementToEdit(Code, R));
474   return Edits;
475 }
476 
477 llvm::Optional<std::string> getCanonicalPath(const FileEntry *F,
478                                              const SourceManager &SourceMgr) {
479   if (!F)
480     return None;
481 
482   llvm::SmallString<128> FilePath = F->getName();
483   if (!llvm::sys::path::is_absolute(FilePath)) {
484     if (auto EC =
485             SourceMgr.getFileManager().getVirtualFileSystem().makeAbsolute(
486                 FilePath)) {
487       elog("Could not turn relative path '{0}' to absolute: {1}", FilePath,
488            EC.message());
489       return None;
490     }
491   }
492 
493   // Handle the symbolic link path case where the current working directory
494   // (getCurrentWorkingDirectory) is a symlink./ We always want to the real
495   // file path (instead of the symlink path) for the  C++ symbols.
496   //
497   // Consider the following example:
498   //
499   //   src dir: /project/src/foo.h
500   //   current working directory (symlink): /tmp/build -> /project/src/
501   //
502   //  The file path of Symbol is "/project/src/foo.h" instead of
503   //  "/tmp/build/foo.h"
504   if (auto Dir = SourceMgr.getFileManager().getDirectory(
505           llvm::sys::path::parent_path(FilePath))) {
506     llvm::SmallString<128> RealPath;
507     llvm::StringRef DirName = SourceMgr.getFileManager().getCanonicalName(*Dir);
508     llvm::sys::path::append(RealPath, DirName,
509                             llvm::sys::path::filename(FilePath));
510     return RealPath.str().str();
511   }
512 
513   return FilePath.str().str();
514 }
515 
516 TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M,
517                     const LangOptions &L) {
518   TextEdit Result;
519   Result.range =
520       halfOpenToRange(M, Lexer::makeFileCharRange(FixIt.RemoveRange, M, L));
521   Result.newText = FixIt.CodeToInsert;
522   return Result;
523 }
524 
525 bool isRangeConsecutive(const Range &Left, const Range &Right) {
526   return Left.end.line == Right.start.line &&
527          Left.end.character == Right.start.character;
528 }
529 
530 FileDigest digest(llvm::StringRef Content) {
531   uint64_t Hash{llvm::xxHash64(Content)};
532   FileDigest Result;
533   for (unsigned I = 0; I < Result.size(); ++I) {
534     Result[I] = uint8_t(Hash);
535     Hash >>= 8;
536   }
537   return Result;
538 }
539 
540 llvm::Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID) {
541   bool Invalid = false;
542   llvm::StringRef Content = SM.getBufferData(FID, &Invalid);
543   if (Invalid)
544     return None;
545   return digest(Content);
546 }
547 
548 format::FormatStyle getFormatStyleForFile(llvm::StringRef File,
549                                           llvm::StringRef Content,
550                                           llvm::vfs::FileSystem *FS) {
551   auto Style = format::getStyle(format::DefaultFormatStyle, File,
552                                 format::DefaultFallbackStyle, Content, FS);
553   if (!Style) {
554     log("getStyle() failed for file {0}: {1}. Fallback is LLVM style.", File,
555         Style.takeError());
556     Style = format::getLLVMStyle();
557   }
558   return *Style;
559 }
560 
561 llvm::Expected<tooling::Replacements>
562 cleanupAndFormat(StringRef Code, const tooling::Replacements &Replaces,
563                  const format::FormatStyle &Style) {
564   auto CleanReplaces = cleanupAroundReplacements(Code, Replaces, Style);
565   if (!CleanReplaces)
566     return CleanReplaces;
567   return formatReplacements(Code, std::move(*CleanReplaces), Style);
568 }
569 
570 template <typename Action>
571 static void lex(llvm::StringRef Code, const format::FormatStyle &Style,
572                 Action A) {
573   // FIXME: InMemoryFileAdapter crashes unless the buffer is null terminated!
574   std::string NullTerminatedCode = Code.str();
575   SourceManagerForFile FileSM("dummy.cpp", NullTerminatedCode);
576   auto &SM = FileSM.get();
577   auto FID = SM.getMainFileID();
578   Lexer Lex(FID, SM.getBuffer(FID), SM, format::getFormattingLangOpts(Style));
579   Token Tok;
580 
581   while (!Lex.LexFromRawLexer(Tok))
582     A(Tok);
583 }
584 
585 llvm::StringMap<unsigned> collectIdentifiers(llvm::StringRef Content,
586                                              const format::FormatStyle &Style) {
587   llvm::StringMap<unsigned> Identifiers;
588   lex(Content, Style, [&](const clang::Token &Tok) {
589     switch (Tok.getKind()) {
590     case tok::identifier:
591       ++Identifiers[Tok.getIdentifierInfo()->getName()];
592       break;
593     case tok::raw_identifier:
594       ++Identifiers[Tok.getRawIdentifier()];
595       break;
596     default:
597       break;
598     }
599   });
600   return Identifiers;
601 }
602 
603 namespace {
604 enum NamespaceEvent {
605   BeginNamespace, // namespace <ns> {.     Payload is resolved <ns>.
606   EndNamespace,   // } // namespace <ns>.  Payload is resolved *outer* namespace.
607   UsingDirective  // using namespace <ns>. Payload is unresolved <ns>.
608 };
609 // Scans C++ source code for constructs that change the visible namespaces.
610 void parseNamespaceEvents(
611     llvm::StringRef Code, const format::FormatStyle &Style,
612     llvm::function_ref<void(NamespaceEvent, llvm::StringRef)> Callback) {
613 
614   // Stack of enclosing namespaces, e.g. {"clang", "clangd"}
615   std::vector<std::string> Enclosing; // Contains e.g. "clang", "clangd"
616   // Stack counts open braces. true if the brace opened a namespace.
617   std::vector<bool> BraceStack;
618 
619   enum {
620     Default,
621     Namespace,          // just saw 'namespace'
622     NamespaceName,      // just saw 'namespace' NSName
623     Using,              // just saw 'using'
624     UsingNamespace,     // just saw 'using namespace'
625     UsingNamespaceName, // just saw 'using namespace' NSName
626   } State = Default;
627   std::string NSName;
628 
629   lex(Code, Style, [&](const clang::Token &Tok) {
630     switch(Tok.getKind()) {
631     case tok::raw_identifier:
632       // In raw mode, this could be a keyword or a name.
633       switch (State) {
634       case UsingNamespace:
635       case UsingNamespaceName:
636         NSName.append(Tok.getRawIdentifier());
637         State = UsingNamespaceName;
638         break;
639       case Namespace:
640       case NamespaceName:
641         NSName.append(Tok.getRawIdentifier());
642         State = NamespaceName;
643         break;
644       case Using:
645         State =
646             (Tok.getRawIdentifier() == "namespace") ? UsingNamespace : Default;
647         break;
648       case Default:
649         NSName.clear();
650         if (Tok.getRawIdentifier() == "namespace")
651           State = Namespace;
652         else if (Tok.getRawIdentifier() == "using")
653           State = Using;
654         break;
655       }
656       break;
657     case tok::coloncolon:
658       // This can come at the beginning or in the middle of a namespace name.
659       switch (State) {
660       case UsingNamespace:
661       case UsingNamespaceName:
662         NSName.append("::");
663         State = UsingNamespaceName;
664         break;
665       case NamespaceName:
666         NSName.append("::");
667         State = NamespaceName;
668         break;
669       case Namespace: // Not legal here.
670       case Using:
671       case Default:
672         State = Default;
673         break;
674       }
675       break;
676     case tok::l_brace:
677       // Record which { started a namespace, so we know when } ends one.
678       if (State == NamespaceName) {
679         // Parsed: namespace <name> {
680         BraceStack.push_back(true);
681         Enclosing.push_back(NSName);
682         Callback(BeginNamespace, llvm::join(Enclosing, "::"));
683       } else {
684         // This case includes anonymous namespaces (State = Namespace).
685         // For our purposes, they're not namespaces and we ignore them.
686         BraceStack.push_back(false);
687       }
688       State = Default;
689       break;
690     case tok::r_brace:
691       // If braces are unmatched, we're going to be confused, but don't crash.
692       if (!BraceStack.empty()) {
693         if (BraceStack.back()) {
694           // Parsed: } // namespace
695           Enclosing.pop_back();
696           Callback(EndNamespace, llvm::join(Enclosing, "::"));
697         }
698         BraceStack.pop_back();
699       }
700       break;
701     case tok::semi:
702       if (State == UsingNamespaceName)
703         // Parsed: using namespace <name> ;
704         Callback(UsingDirective, llvm::StringRef(NSName));
705       State = Default;
706       break;
707     default:
708       State = Default;
709       break;
710     }
711   });
712 }
713 
714 // Returns the prefix namespaces of NS: {"" ... NS}.
715 llvm::SmallVector<llvm::StringRef, 8> ancestorNamespaces(llvm::StringRef NS) {
716   llvm::SmallVector<llvm::StringRef, 8> Results;
717   Results.push_back(NS.take_front(0));
718   NS.split(Results, "::", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
719   for (llvm::StringRef &R : Results)
720     R = NS.take_front(R.end() - NS.begin());
721   return Results;
722 }
723 
724 } // namespace
725 
726 std::vector<std::string> visibleNamespaces(llvm::StringRef Code,
727                                            const format::FormatStyle &Style) {
728   std::string Current;
729   // Map from namespace to (resolved) namespaces introduced via using directive.
730   llvm::StringMap<llvm::StringSet<>> UsingDirectives;
731 
732   parseNamespaceEvents(Code, Style,
733                        [&](NamespaceEvent Event, llvm::StringRef NS) {
734                          switch (Event) {
735                          case BeginNamespace:
736                          case EndNamespace:
737                            Current = NS;
738                            break;
739                          case UsingDirective:
740                            if (NS.consume_front("::"))
741                              UsingDirectives[Current].insert(NS);
742                            else {
743                              for (llvm::StringRef Enclosing :
744                                   ancestorNamespaces(Current)) {
745                                if (Enclosing.empty())
746                                  UsingDirectives[Current].insert(NS);
747                                else
748                                  UsingDirectives[Current].insert(
749                                      (Enclosing + "::" + NS).str());
750                              }
751                            }
752                            break;
753                          }
754                        });
755 
756   std::vector<std::string> Found;
757   for (llvm::StringRef Enclosing : ancestorNamespaces(Current)) {
758     Found.push_back(Enclosing);
759     auto It = UsingDirectives.find(Enclosing);
760     if (It != UsingDirectives.end())
761       for (const auto& Used : It->second)
762         Found.push_back(Used.getKey());
763   }
764 
765   llvm::sort(Found, [&](const std::string &LHS, const std::string &RHS) {
766     if (Current == RHS)
767       return false;
768     if (Current == LHS)
769       return true;
770     return LHS < RHS;
771   });
772   Found.erase(std::unique(Found.begin(), Found.end()), Found.end());
773   return Found;
774 }
775 
776 llvm::StringSet<> collectWords(llvm::StringRef Content) {
777   // We assume short words are not significant.
778   // We may want to consider other stopwords, e.g. language keywords.
779   // (A very naive implementation showed no benefit, but lexing might do better)
780   static constexpr int MinWordLength = 4;
781 
782   std::vector<CharRole> Roles(Content.size());
783   calculateRoles(Content, Roles);
784 
785   llvm::StringSet<> Result;
786   llvm::SmallString<256> Word;
787   auto Flush = [&] {
788     if (Word.size() >= MinWordLength) {
789       for (char &C : Word)
790         C = llvm::toLower(C);
791       Result.insert(Word);
792     }
793     Word.clear();
794   };
795   for (unsigned I = 0; I < Content.size(); ++I) {
796     switch (Roles[I]) {
797     case Head:
798       Flush();
799       LLVM_FALLTHROUGH;
800     case Tail:
801       Word.push_back(Content[I]);
802       break;
803     case Unknown:
804     case Separator:
805       Flush();
806       break;
807     }
808   }
809   Flush();
810 
811   return Result;
812 }
813 
814 llvm::Optional<DefinedMacro> locateMacroAt(SourceLocation Loc,
815                                            Preprocessor &PP) {
816   const auto &SM = PP.getSourceManager();
817   const auto &LangOpts = PP.getLangOpts();
818   Token Result;
819   if (Lexer::getRawToken(SM.getSpellingLoc(Loc), Result, SM, LangOpts, false))
820     return None;
821   if (Result.is(tok::raw_identifier))
822     PP.LookUpIdentifierInfo(Result);
823   IdentifierInfo *IdentifierInfo = Result.getIdentifierInfo();
824   if (!IdentifierInfo || !IdentifierInfo->hadMacroDefinition())
825     return None;
826 
827   std::pair<FileID, unsigned int> DecLoc = SM.getDecomposedExpansionLoc(Loc);
828   // Get the definition just before the searched location so that a macro
829   // referenced in a '#undef MACRO' can still be found.
830   SourceLocation BeforeSearchedLocation =
831       SM.getMacroArgExpandedLocation(SM.getLocForStartOfFile(DecLoc.first)
832                                          .getLocWithOffset(DecLoc.second - 1));
833   MacroDefinition MacroDef =
834       PP.getMacroDefinitionAtLoc(IdentifierInfo, BeforeSearchedLocation);
835   if (auto *MI = MacroDef.getMacroInfo())
836     return DefinedMacro{IdentifierInfo->getName(), MI};
837   return None;
838 }
839 
840 } // namespace clangd
841 } // namespace clang
842