blob: 05ca7aaaa1e86981bf2f83f2e98e4d39a5f0faac [file] [log] [blame]
Sam McCallb536a2a2017-12-19 12:23:48 +00001//===--- SourceCode.h - Manipulating source code as strings -----*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Sam McCallb536a2a2017-12-19 12:23:48 +00006//
7//===----------------------------------------------------------------------===//
8#include "SourceCode.h"
9
Sam McCalla69698f2019-03-27 17:47:49 +000010#include "Context.h"
Sam McCall9fb22b22019-05-06 10:25:10 +000011#include "FuzzyMatch.h"
Marc-Andre Laperle1be69702018-07-05 19:35:01 +000012#include "Logger.h"
Sam McCalla69698f2019-03-27 17:47:49 +000013#include "Protocol.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000014#include "refactor/Tweak.h"
Marc-Andre Laperle1be69702018-07-05 19:35:01 +000015#include "clang/AST/ASTContext.h"
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +000016#include "clang/Basic/LangOptions.h"
17#include "clang/Basic/SourceLocation.h"
Marc-Andre Laperle63a10982018-02-21 02:39:08 +000018#include "clang/Basic/SourceManager.h"
Sam McCallc316b222019-04-26 07:45:49 +000019#include "clang/Basic/TokenKinds.h"
20#include "clang/Format/Format.h"
Marc-Andre Laperle1be69702018-07-05 19:35:01 +000021#include "clang/Lex/Lexer.h"
Haojian Wu9d34f452019-07-01 09:26:48 +000022#include "clang/Lex/Preprocessor.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000023#include "clang/Tooling/Core/Replacement.h"
24#include "llvm/ADT/ArrayRef.h"
Ilya Biryukov43998782019-01-31 21:30:05 +000025#include "llvm/ADT/None.h"
Sam McCallc316b222019-04-26 07:45:49 +000026#include "llvm/ADT/StringExtras.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000027#include "llvm/ADT/StringMap.h"
Ilya Biryukov43998782019-01-31 21:30:05 +000028#include "llvm/ADT/StringRef.h"
Sam McCall9fb22b22019-05-06 10:25:10 +000029#include "llvm/Support/Compiler.h"
Simon Marchi766338a2018-03-21 14:36:46 +000030#include "llvm/Support/Errc.h"
31#include "llvm/Support/Error.h"
Sam McCall8b25d222019-03-28 14:37:51 +000032#include "llvm/Support/ErrorHandling.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000033#include "llvm/Support/LineIterator.h"
34#include "llvm/Support/MemoryBuffer.h"
Marc-Andre Laperle1be69702018-07-05 19:35:01 +000035#include "llvm/Support/Path.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000036#include "llvm/Support/SHA1.h"
37#include "llvm/Support/VirtualFileSystem.h"
Sam McCall674d8a92019-07-08 11:33:17 +000038#include "llvm/Support/xxhash.h"
Sam McCallc316b222019-04-26 07:45:49 +000039#include <algorithm>
Marc-Andre Laperle63a10982018-02-21 02:39:08 +000040
Sam McCallb536a2a2017-12-19 12:23:48 +000041namespace clang {
42namespace clangd {
Sam McCallb536a2a2017-12-19 12:23:48 +000043
Sam McCalla4962cc2018-04-27 11:59:28 +000044// 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.
50template <typename Callback>
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000051static bool iterateCodepoints(llvm::StringRef U8, const Callback &CB) {
Sam McCall8b25d222019-03-28 14:37:51 +000052 // 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.
Sam McCalla4962cc2018-04-27 11:59:28 +000054 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.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000063 size_t UTF8Length = llvm::countLeadingOnes(C);
Sam McCalla4962cc2018-04-27 11:59:28 +000064 // 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
Sam McCall8b25d222019-03-28 14:37:51 +000077// 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.
81static size_t measureUnits(llvm::StringRef U8, int Units, OffsetEncoding Enc,
82 bool &Valid) {
83 Valid = Units >= 0;
84 if (Units <= 0)
85 return 0;
Sam McCalla4962cc2018-04-27 11:59:28 +000086 size_t Result = 0;
Sam McCall8b25d222019-03-28 14:37:51 +000087 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 }
Sam McCalla4962cc2018-04-27 11:59:28 +0000110 // Don't return an out-of-range index if we overran.
Sam McCall8b25d222019-03-28 14:37:51 +0000111 if (Result > U8.size()) {
112 Valid = false;
113 return U8.size();
114 }
115 return Result;
Sam McCalla4962cc2018-04-27 11:59:28 +0000116}
117
Sam McCalla69698f2019-03-27 17:47:49 +0000118Key<OffsetEncoding> kCurrentOffsetEncoding;
Sam McCall8b25d222019-03-28 14:37:51 +0000119static OffsetEncoding lspEncoding() {
Sam McCalla69698f2019-03-27 17:47:49 +0000120 auto *Enc = Context::current().get(kCurrentOffsetEncoding);
Sam McCall8b25d222019-03-28 14:37:51 +0000121 return Enc ? *Enc : OffsetEncoding::UTF16;
Sam McCalla69698f2019-03-27 17:47:49 +0000122}
123
Sam McCalla4962cc2018-04-27 11:59:28 +0000124// Like most strings in clangd, the input is UTF-8 encoded.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000125size_t lspLength(llvm::StringRef Code) {
Sam McCalla4962cc2018-04-27 11:59:28 +0000126 size_t Count = 0;
Sam McCall8b25d222019-03-28 14:37:51 +0000127 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 }
Sam McCalla4962cc2018-04-27 11:59:28 +0000146 return Count;
147}
148
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000149llvm::Expected<size_t> positionToOffset(llvm::StringRef Code, Position P,
150 bool AllowColumnsBeyondLineLength) {
Sam McCallb536a2a2017-12-19 12:23:48 +0000151 if (P.line < 0)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000152 return llvm::make_error<llvm::StringError>(
153 llvm::formatv("Line value can't be negative ({0})", P.line),
154 llvm::errc::invalid_argument);
Simon Marchi766338a2018-03-21 14:36:46 +0000155 if (P.character < 0)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000156 return llvm::make_error<llvm::StringError>(
157 llvm::formatv("Character value can't be negative ({0})", P.character),
158 llvm::errc::invalid_argument);
Sam McCallb536a2a2017-12-19 12:23:48 +0000159 size_t StartOfLine = 0;
160 for (int I = 0; I != P.line; ++I) {
161 size_t NextNL = Code.find('\n', StartOfLine);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000162 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);
Sam McCallb536a2a2017-12-19 12:23:48 +0000166 StartOfLine = NextNL + 1;
167 }
Sam McCalla69698f2019-03-27 17:47:49 +0000168 StringRef Line =
169 Code.substr(StartOfLine).take_until([](char C) { return C == '\n'; });
Simon Marchi766338a2018-03-21 14:36:46 +0000170
Sam McCall8b25d222019-03-28 14:37:51 +0000171 // P.character may be in UTF-16, transcode if necessary.
Sam McCalla4962cc2018-04-27 11:59:28 +0000172 bool Valid;
Sam McCall8b25d222019-03-28 14:37:51 +0000173 size_t ByteInLine = measureUnits(Line, P.character, lspEncoding(), Valid);
Sam McCalla4962cc2018-04-27 11:59:28 +0000174 if (!Valid && !AllowColumnsBeyondLineLength)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000175 return llvm::make_error<llvm::StringError>(
Sam McCall8b25d222019-03-28 14:37:51 +0000176 llvm::formatv("{0} offset {1} is invalid for line {2}", lspEncoding(),
177 P.character, P.line),
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000178 llvm::errc::invalid_argument);
Sam McCall8b25d222019-03-28 14:37:51 +0000179 return StartOfLine + ByteInLine;
Sam McCallb536a2a2017-12-19 12:23:48 +0000180}
181
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000182Position offsetToPosition(llvm::StringRef Code, size_t Offset) {
Sam McCallb536a2a2017-12-19 12:23:48 +0000183 Offset = std::min(Code.size(), Offset);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000184 llvm::StringRef Before = Code.substr(0, Offset);
Sam McCallb536a2a2017-12-19 12:23:48 +0000185 int Lines = Before.count('\n');
186 size_t PrevNL = Before.rfind('\n');
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000187 size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
Ilya Biryukov7beea3a2018-02-14 10:52:04 +0000188 Position Pos;
189 Pos.line = Lines;
Sam McCall71891122018-10-23 11:51:53 +0000190 Pos.character = lspLength(Before.substr(StartOfLine));
Ilya Biryukov7beea3a2018-02-14 10:52:04 +0000191 return Pos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000192}
193
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000194Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc) {
Sam McCalla4962cc2018-04-27 11:59:28 +0000195 // 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);
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000199 Position P;
Sam McCalla4962cc2018-04-27 11:59:28 +0000200 P.line = static_cast<int>(SM.getLineNumber(FID, Offset)) - 1;
201 bool Invalid = false;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000202 llvm::StringRef Code = SM.getBufferData(FID, &Invalid);
Sam McCalla4962cc2018-04-27 11:59:28 +0000203 if (!Invalid) {
204 auto ColumnInBytes = SM.getColumnNumber(FID, Offset) - 1;
205 auto LineSoFar = Code.substr(Offset - ColumnInBytes, ColumnInBytes);
Sam McCall71891122018-10-23 11:51:53 +0000206 P.character = lspLength(LineSoFar);
Sam McCalla4962cc2018-04-27 11:59:28 +0000207 }
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000208 return P;
209}
210
Sam McCall95738072019-08-06 20:25:59 +0000211bool 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
221SourceLocation 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
Haojian Wu92c32572019-06-25 08:01:46 +0000229llvm::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
Haojian Wu9f2bf662019-10-01 11:03:56 +0000240namespace {
241
242enum TokenFlavor { Identifier, Operator, Whitespace, Other };
243
244bool isOverloadedOperator(const Token &Tok) {
245 switch (Tok.getKind()) {
246#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemOnly) \
247 case tok::Token:
248#define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemOnly)
249#include "clang/Basic/OperatorKinds.def"
250 return true;
251
252 default:
253 break;
254 }
255 return false;
256}
257
258TokenFlavor getTokenFlavor(SourceLocation Loc, const SourceManager &SM,
259 const LangOptions &LangOpts) {
260 Token Tok;
261 Tok.setKind(tok::NUM_TOKENS);
262 if (Lexer::getRawToken(Loc, Tok, SM, LangOpts,
263 /*IgnoreWhiteSpace*/ false))
264 return Other;
265
266 // getRawToken will return false without setting Tok when the token is
267 // whitespace, so if the flag is not set, we are sure this is a whitespace.
268 if (Tok.is(tok::TokenKind::NUM_TOKENS))
269 return Whitespace;
270 if (Tok.is(tok::TokenKind::raw_identifier))
271 return Identifier;
272 if (isOverloadedOperator(Tok))
273 return Operator;
274 return Other;
275}
276
277} // namespace
278
Sam McCall19cefc22019-09-03 15:34:47 +0000279SourceLocation getBeginningOfIdentifier(const Position &Pos,
280 const SourceManager &SM,
281 const LangOptions &LangOpts) {
282 FileID FID = SM.getMainFileID();
283 auto Offset = positionToOffset(SM.getBufferData(FID), Pos);
284 if (!Offset) {
285 log("getBeginningOfIdentifier: {0}", Offset.takeError());
286 return SourceLocation();
287 }
288
Haojian Wu9f2bf662019-10-01 11:03:56 +0000289 // GetBeginningOfToken(InputLoc) is almost what we want, but does the wrong
290 // thing if the cursor is at the end of the token (identifier or operator).
291 // The cases are:
292 // 1) at the beginning of the token
293 // 2) at the middle of the token
294 // 3) at the end of the token
295 // 4) anywhere outside the identifier or operator
296 // To distinguish all cases, we lex both at the
297 // GetBeginningOfToken(InputLoc-1) and GetBeginningOfToken(InputLoc), for
298 // cases 1 and 4, we just return the original location.
Sam McCall19cefc22019-09-03 15:34:47 +0000299 SourceLocation InputLoc = SM.getComposedLoc(FID, *Offset);
Haojian Wu9f2bf662019-10-01 11:03:56 +0000300 if (*Offset == 0) // Case 1 or 4.
Sam McCallb2a984c02019-09-04 10:15:27 +0000301 return InputLoc;
Sam McCall19cefc22019-09-03 15:34:47 +0000302 SourceLocation Before = SM.getComposedLoc(FID, *Offset - 1);
Haojian Wu9f2bf662019-10-01 11:03:56 +0000303 SourceLocation BeforeTokBeginning =
304 Lexer::GetBeginningOfToken(Before, SM, LangOpts);
305 TokenFlavor BeforeKind = getTokenFlavor(BeforeTokBeginning, SM, LangOpts);
Sam McCall19cefc22019-09-03 15:34:47 +0000306
Haojian Wu9f2bf662019-10-01 11:03:56 +0000307 SourceLocation CurrentTokBeginning =
308 Lexer::GetBeginningOfToken(InputLoc, SM, LangOpts);
309 TokenFlavor CurrentKind = getTokenFlavor(CurrentTokBeginning, SM, LangOpts);
310
311 // At the middle of the token.
312 if (BeforeTokBeginning == CurrentTokBeginning) {
313 // For interesting token, we return the beginning of the token.
314 if (CurrentKind == Identifier || CurrentKind == Operator)
315 return CurrentTokBeginning;
316 // otherwise, we return the original loc.
317 return InputLoc;
318 }
319
320 // Whitespace is not interesting.
321 if (BeforeKind == Whitespace)
322 return CurrentTokBeginning;
323 if (CurrentKind == Whitespace)
324 return BeforeTokBeginning;
325
326 // The cursor is at the token boundary, e.g. "Before^Current", we prefer
327 // identifiers to other tokens.
328 if (CurrentKind == Identifier)
329 return CurrentTokBeginning;
330 if (BeforeKind == Identifier)
331 return BeforeTokBeginning;
332 // Then prefer overloaded operators to other tokens.
333 if (CurrentKind == Operator)
334 return CurrentTokBeginning;
335 if (BeforeKind == Operator)
336 return BeforeTokBeginning;
337
338 // Non-interesting case, we just return the original location.
339 return InputLoc;
Sam McCall19cefc22019-09-03 15:34:47 +0000340}
341
Ilya Biryukov43998782019-01-31 21:30:05 +0000342bool isValidFileRange(const SourceManager &Mgr, SourceRange R) {
343 if (!R.getBegin().isValid() || !R.getEnd().isValid())
344 return false;
345
346 FileID BeginFID;
347 size_t BeginOffset = 0;
348 std::tie(BeginFID, BeginOffset) = Mgr.getDecomposedLoc(R.getBegin());
349
350 FileID EndFID;
351 size_t EndOffset = 0;
352 std::tie(EndFID, EndOffset) = Mgr.getDecomposedLoc(R.getEnd());
353
354 return BeginFID.isValid() && BeginFID == EndFID && BeginOffset <= EndOffset;
355}
356
357bool halfOpenRangeContains(const SourceManager &Mgr, SourceRange R,
358 SourceLocation L) {
359 assert(isValidFileRange(Mgr, R));
360
361 FileID BeginFID;
362 size_t BeginOffset = 0;
363 std::tie(BeginFID, BeginOffset) = Mgr.getDecomposedLoc(R.getBegin());
364 size_t EndOffset = Mgr.getFileOffset(R.getEnd());
365
366 FileID LFid;
367 size_t LOffset;
368 std::tie(LFid, LOffset) = Mgr.getDecomposedLoc(L);
369 return BeginFID == LFid && BeginOffset <= LOffset && LOffset < EndOffset;
370}
371
372bool halfOpenRangeTouches(const SourceManager &Mgr, SourceRange R,
373 SourceLocation L) {
374 return L == R.getEnd() || halfOpenRangeContains(Mgr, R, L);
375}
376
Sam McCallc791d852019-08-27 08:44:06 +0000377SourceLocation includeHashLoc(FileID IncludedFile, const SourceManager &SM) {
378 assert(SM.getLocForEndOfFile(IncludedFile).isFileID());
379 FileID IncludingFile;
380 unsigned Offset;
381 std::tie(IncludingFile, Offset) =
382 SM.getDecomposedExpansionLoc(SM.getIncludeLoc(IncludedFile));
383 bool Invalid = false;
384 llvm::StringRef Buf = SM.getBufferData(IncludingFile, &Invalid);
385 if (Invalid)
386 return SourceLocation();
387 // Now buf is "...\n#include <foo>\n..."
388 // and Offset points here: ^
389 // Rewind to the preceding # on the line.
390 assert(Offset < Buf.size());
391 for (;; --Offset) {
392 if (Buf[Offset] == '#')
393 return SM.getComposedLoc(IncludingFile, Offset);
394 if (Buf[Offset] == '\n' || Offset == 0) // no hash, what's going on?
395 return SourceLocation();
396 }
397}
398
399
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000400static unsigned getTokenLengthAtLoc(SourceLocation Loc, const SourceManager &SM,
401 const LangOptions &LangOpts) {
402 Token TheTok;
403 if (Lexer::getRawToken(Loc, TheTok, SM, LangOpts))
404 return 0;
405 // FIXME: Here we check whether the token at the location is a greatergreater
406 // (>>) token and consider it as a single greater (>). This is to get it
407 // working for templates but it isn't correct for the right shift operator. We
408 // can avoid this by using half open char ranges in getFileRange() but getting
409 // token ending is not well supported in macroIDs.
410 if (TheTok.is(tok::greatergreater))
411 return 1;
412 return TheTok.getLength();
413}
414
415// Returns location of the last character of the token at a given loc
416static SourceLocation getLocForTokenEnd(SourceLocation BeginLoc,
417 const SourceManager &SM,
418 const LangOptions &LangOpts) {
419 unsigned Len = getTokenLengthAtLoc(BeginLoc, SM, LangOpts);
420 return BeginLoc.getLocWithOffset(Len ? Len - 1 : 0);
421}
422
423// Returns location of the starting of the token at a given EndLoc
424static SourceLocation getLocForTokenBegin(SourceLocation EndLoc,
425 const SourceManager &SM,
426 const LangOptions &LangOpts) {
427 return EndLoc.getLocWithOffset(
428 -(signed)getTokenLengthAtLoc(EndLoc, SM, LangOpts));
429}
430
431// Converts a char source range to a token range.
432static SourceRange toTokenRange(CharSourceRange Range, const SourceManager &SM,
433 const LangOptions &LangOpts) {
434 if (!Range.isTokenRange())
435 Range.setEnd(getLocForTokenBegin(Range.getEnd(), SM, LangOpts));
436 return Range.getAsRange();
437}
438// Returns the union of two token ranges.
439// To find the maximum of the Ends of the ranges, we compare the location of the
440// last character of the token.
441static SourceRange unionTokenRange(SourceRange R1, SourceRange R2,
442 const SourceManager &SM,
443 const LangOptions &LangOpts) {
Sam McCallc791d852019-08-27 08:44:06 +0000444 SourceLocation Begin =
445 SM.isBeforeInTranslationUnit(R1.getBegin(), R2.getBegin())
446 ? R1.getBegin()
447 : R2.getBegin();
448 SourceLocation End =
449 SM.isBeforeInTranslationUnit(getLocForTokenEnd(R1.getEnd(), SM, LangOpts),
450 getLocForTokenEnd(R2.getEnd(), SM, LangOpts))
451 ? R2.getEnd()
452 : R1.getEnd();
453 return SourceRange(Begin, End);
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000454}
455
Sam McCallc791d852019-08-27 08:44:06 +0000456// Given a range whose endpoints may be in different expansions or files,
457// tries to find a range within a common file by following up the expansion and
458// include location in each.
459static SourceRange rangeInCommonFile(SourceRange R, const SourceManager &SM,
460 const LangOptions &LangOpts) {
461 // Fast path for most common cases.
462 if (SM.isWrittenInSameFile(R.getBegin(), R.getEnd()))
463 return R;
464 // Record the stack of expansion locations for the beginning, keyed by FileID.
465 llvm::DenseMap<FileID, SourceLocation> BeginExpansions;
466 for (SourceLocation Begin = R.getBegin(); Begin.isValid();
467 Begin = Begin.isFileID()
468 ? includeHashLoc(SM.getFileID(Begin), SM)
469 : SM.getImmediateExpansionRange(Begin).getBegin()) {
470 BeginExpansions[SM.getFileID(Begin)] = Begin;
471 }
472 // Move up the stack of expansion locations for the end until we find the
473 // location in BeginExpansions with that has the same file id.
474 for (SourceLocation End = R.getEnd(); End.isValid();
475 End = End.isFileID() ? includeHashLoc(SM.getFileID(End), SM)
476 : toTokenRange(SM.getImmediateExpansionRange(End),
477 SM, LangOpts)
478 .getEnd()) {
479 auto It = BeginExpansions.find(SM.getFileID(End));
480 if (It != BeginExpansions.end()) {
481 if (SM.getFileOffset(It->second) > SM.getFileOffset(End))
482 return SourceLocation();
483 return {It->second, End};
484 }
485 }
486 return SourceRange();
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000487}
488
489// Find an expansion range (not necessarily immediate) the ends of which are in
490// the same file id.
491static SourceRange
492getExpansionTokenRangeInSameFile(SourceLocation Loc, const SourceManager &SM,
493 const LangOptions &LangOpts) {
Sam McCallc791d852019-08-27 08:44:06 +0000494 return rangeInCommonFile(
495 toTokenRange(SM.getImmediateExpansionRange(Loc), SM, LangOpts), SM,
496 LangOpts);
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000497}
Sam McCallc791d852019-08-27 08:44:06 +0000498
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000499// Returns the file range for a given Location as a Token Range
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000500// This is quite similar to getFileLoc in SourceManager as both use
501// getImmediateExpansionRange and getImmediateSpellingLoc (for macro IDs).
502// However:
503// - We want to maintain the full range information as we move from one file to
504// the next. getFileLoc only uses the BeginLoc of getImmediateExpansionRange.
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000505// - We want to split '>>' tokens as the lexer parses the '>>' in nested
506// template instantiations as a '>>' instead of two '>'s.
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000507// There is also getExpansionRange but it simply calls
508// getImmediateExpansionRange on the begin and ends separately which is wrong.
509static SourceRange getTokenFileRange(SourceLocation Loc,
510 const SourceManager &SM,
511 const LangOptions &LangOpts) {
512 SourceRange FileRange = Loc;
513 while (!FileRange.getBegin().isFileID()) {
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000514 if (SM.isMacroArgExpansion(FileRange.getBegin())) {
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000515 FileRange = unionTokenRange(
516 SM.getImmediateSpellingLoc(FileRange.getBegin()),
517 SM.getImmediateSpellingLoc(FileRange.getEnd()), SM, LangOpts);
Sam McCallc791d852019-08-27 08:44:06 +0000518 assert(SM.isWrittenInSameFile(FileRange.getBegin(), FileRange.getEnd()));
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000519 } else {
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000520 SourceRange ExpansionRangeForBegin =
521 getExpansionTokenRangeInSameFile(FileRange.getBegin(), SM, LangOpts);
522 SourceRange ExpansionRangeForEnd =
523 getExpansionTokenRangeInSameFile(FileRange.getEnd(), SM, LangOpts);
Sam McCallc791d852019-08-27 08:44:06 +0000524 if (ExpansionRangeForBegin.isInvalid() ||
525 ExpansionRangeForEnd.isInvalid())
526 return SourceRange();
527 assert(SM.isWrittenInSameFile(ExpansionRangeForBegin.getBegin(),
528 ExpansionRangeForEnd.getBegin()) &&
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000529 "Both Expansion ranges should be in same file.");
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000530 FileRange = unionTokenRange(ExpansionRangeForBegin, ExpansionRangeForEnd,
531 SM, LangOpts);
532 }
533 }
534 return FileRange;
535}
536
Haojian Wu6ae86ea2019-07-19 08:33:39 +0000537bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM) {
538 return Loc.isValid() && SM.isWrittenInMainFile(SM.getExpansionLoc(Loc));
539}
540
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000541llvm::Optional<SourceRange> toHalfOpenFileRange(const SourceManager &SM,
Ilya Biryukov43998782019-01-31 21:30:05 +0000542 const LangOptions &LangOpts,
543 SourceRange R) {
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000544 SourceRange R1 = getTokenFileRange(R.getBegin(), SM, LangOpts);
545 if (!isValidFileRange(SM, R1))
Ilya Biryukov43998782019-01-31 21:30:05 +0000546 return llvm::None;
Ilya Biryukov43998782019-01-31 21:30:05 +0000547
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000548 SourceRange R2 = getTokenFileRange(R.getEnd(), SM, LangOpts);
549 if (!isValidFileRange(SM, R2))
Ilya Biryukov43998782019-01-31 21:30:05 +0000550 return llvm::None;
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000551
Sam McCallc791d852019-08-27 08:44:06 +0000552 SourceRange Result =
553 rangeInCommonFile(unionTokenRange(R1, R2, SM, LangOpts), SM, LangOpts);
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000554 unsigned TokLen = getTokenLengthAtLoc(Result.getEnd(), SM, LangOpts);
555 // Convert from closed token range to half-open (char) range
556 Result.setEnd(Result.getEnd().getLocWithOffset(TokLen));
557 if (!isValidFileRange(SM, Result))
558 return llvm::None;
559
Ilya Biryukov43998782019-01-31 21:30:05 +0000560 return Result;
561}
562
563llvm::StringRef toSourceCode(const SourceManager &SM, SourceRange R) {
564 assert(isValidFileRange(SM, R));
565 bool Invalid = false;
566 auto *Buf = SM.getBuffer(SM.getFileID(R.getBegin()), &Invalid);
567 assert(!Invalid);
568
569 size_t BeginOffset = SM.getFileOffset(R.getBegin());
570 size_t EndOffset = SM.getFileOffset(R.getEnd());
571 return Buf->getBuffer().substr(BeginOffset, EndOffset - BeginOffset);
572}
573
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000574llvm::Expected<SourceLocation> sourceLocationInMainFile(const SourceManager &SM,
575 Position P) {
576 llvm::StringRef Code = SM.getBuffer(SM.getMainFileID())->getBuffer();
577 auto Offset =
578 positionToOffset(Code, P, /*AllowColumnBeyondLineLength=*/false);
579 if (!Offset)
580 return Offset.takeError();
581 return SM.getLocForStartOfFile(SM.getMainFileID()).getLocWithOffset(*Offset);
582}
583
Ilya Biryukov71028b82018-03-12 15:28:22 +0000584Range halfOpenToRange(const SourceManager &SM, CharSourceRange R) {
585 // Clang is 1-based, LSP uses 0-based indexes.
586 Position Begin = sourceLocToPosition(SM, R.getBegin());
587 Position End = sourceLocToPosition(SM, R.getEnd());
588
589 return {Begin, End};
590}
591
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000592std::pair<size_t, size_t> offsetToClangLineColumn(llvm::StringRef Code,
Sam McCalla4962cc2018-04-27 11:59:28 +0000593 size_t Offset) {
594 Offset = std::min(Code.size(), Offset);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000595 llvm::StringRef Before = Code.substr(0, Offset);
Sam McCalla4962cc2018-04-27 11:59:28 +0000596 int Lines = Before.count('\n');
597 size_t PrevNL = Before.rfind('\n');
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000598 size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
Sam McCalla4962cc2018-04-27 11:59:28 +0000599 return {Lines + 1, Offset - StartOfLine + 1};
600}
601
Ilya Biryukov43998782019-01-31 21:30:05 +0000602std::pair<StringRef, StringRef> splitQualifiedName(StringRef QName) {
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000603 size_t Pos = QName.rfind("::");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000604 if (Pos == llvm::StringRef::npos)
605 return {llvm::StringRef(), QName};
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000606 return {QName.substr(0, Pos + 2), QName.substr(Pos + 2)};
607}
608
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000609TextEdit replacementToEdit(llvm::StringRef Code,
610 const tooling::Replacement &R) {
Eric Liu9133ecd2018-05-11 12:12:08 +0000611 Range ReplacementRange = {
612 offsetToPosition(Code, R.getOffset()),
613 offsetToPosition(Code, R.getOffset() + R.getLength())};
614 return {ReplacementRange, R.getReplacementText()};
615}
616
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000617std::vector<TextEdit> replacementsToEdits(llvm::StringRef Code,
Eric Liu9133ecd2018-05-11 12:12:08 +0000618 const tooling::Replacements &Repls) {
619 std::vector<TextEdit> Edits;
620 for (const auto &R : Repls)
621 Edits.push_back(replacementToEdit(Code, R));
622 return Edits;
623}
624
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000625llvm::Optional<std::string> getCanonicalPath(const FileEntry *F,
626 const SourceManager &SourceMgr) {
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000627 if (!F)
628 return None;
Simon Marchi25f1f732018-08-10 22:27:53 +0000629
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000630 llvm::SmallString<128> FilePath = F->getName();
631 if (!llvm::sys::path::is_absolute(FilePath)) {
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000632 if (auto EC =
Duncan P. N. Exon Smithdb8a7422019-03-26 22:32:06 +0000633 SourceMgr.getFileManager().getVirtualFileSystem().makeAbsolute(
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000634 FilePath)) {
635 elog("Could not turn relative path '{0}' to absolute: {1}", FilePath,
636 EC.message());
Sam McCallc008af62018-10-20 15:30:37 +0000637 return None;
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000638 }
639 }
Simon Marchi25f1f732018-08-10 22:27:53 +0000640
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000641 // Handle the symbolic link path case where the current working directory
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000642 // (getCurrentWorkingDirectory) is a symlink. We always want to the real
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000643 // file path (instead of the symlink path) for the C++ symbols.
644 //
645 // Consider the following example:
646 //
647 // src dir: /project/src/foo.h
648 // current working directory (symlink): /tmp/build -> /project/src/
649 //
650 // The file path of Symbol is "/project/src/foo.h" instead of
651 // "/tmp/build/foo.h"
Harlan Haskinsa02f8572019-08-01 21:32:01 +0000652 if (auto Dir = SourceMgr.getFileManager().getDirectory(
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000653 llvm::sys::path::parent_path(FilePath))) {
654 llvm::SmallString<128> RealPath;
Harlan Haskinsa02f8572019-08-01 21:32:01 +0000655 llvm::StringRef DirName = SourceMgr.getFileManager().getCanonicalName(*Dir);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000656 llvm::sys::path::append(RealPath, DirName,
657 llvm::sys::path::filename(FilePath));
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000658 return RealPath.str().str();
Simon Marchi25f1f732018-08-10 22:27:53 +0000659 }
660
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000661 return FilePath.str().str();
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000662}
663
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +0000664TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M,
665 const LangOptions &L) {
666 TextEdit Result;
667 Result.range =
668 halfOpenToRange(M, Lexer::makeFileCharRange(FixIt.RemoveRange, M, L));
669 Result.newText = FixIt.CodeToInsert;
670 return Result;
671}
672
Haojian Wuaa3ed5a2019-01-25 15:14:03 +0000673bool isRangeConsecutive(const Range &Left, const Range &Right) {
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +0000674 return Left.end.line == Right.start.line &&
675 Left.end.character == Right.start.character;
676}
677
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000678FileDigest digest(llvm::StringRef Content) {
Sam McCall674d8a92019-07-08 11:33:17 +0000679 uint64_t Hash{llvm::xxHash64(Content)};
680 FileDigest Result;
681 for (unsigned I = 0; I < Result.size(); ++I) {
682 Result[I] = uint8_t(Hash);
683 Hash >>= 8;
684 }
685 return Result;
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000686}
687
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000688llvm::Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID) {
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000689 bool Invalid = false;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000690 llvm::StringRef Content = SM.getBufferData(FID, &Invalid);
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000691 if (Invalid)
692 return None;
693 return digest(Content);
694}
695
Eric Liudd662772019-01-28 14:01:55 +0000696format::FormatStyle getFormatStyleForFile(llvm::StringRef File,
697 llvm::StringRef Content,
698 llvm::vfs::FileSystem *FS) {
699 auto Style = format::getStyle(format::DefaultFormatStyle, File,
700 format::DefaultFallbackStyle, Content, FS);
701 if (!Style) {
702 log("getStyle() failed for file {0}: {1}. Fallback is LLVM style.", File,
703 Style.takeError());
704 Style = format::getLLVMStyle();
705 }
706 return *Style;
707}
708
Haojian Wu12e194c2019-02-06 15:24:50 +0000709llvm::Expected<tooling::Replacements>
710cleanupAndFormat(StringRef Code, const tooling::Replacements &Replaces,
711 const format::FormatStyle &Style) {
712 auto CleanReplaces = cleanupAroundReplacements(Code, Replaces, Style);
713 if (!CleanReplaces)
714 return CleanReplaces;
715 return formatReplacements(Code, std::move(*CleanReplaces), Style);
716}
717
Sam McCallc316b222019-04-26 07:45:49 +0000718template <typename Action>
719static void lex(llvm::StringRef Code, const format::FormatStyle &Style,
720 Action A) {
721 // FIXME: InMemoryFileAdapter crashes unless the buffer is null terminated!
722 std::string NullTerminatedCode = Code.str();
723 SourceManagerForFile FileSM("dummy.cpp", NullTerminatedCode);
Eric Liu00d99bd2019-04-11 09:36:36 +0000724 auto &SM = FileSM.get();
725 auto FID = SM.getMainFileID();
726 Lexer Lex(FID, SM.getBuffer(FID), SM, format::getFormattingLangOpts(Style));
727 Token Tok;
728
Sam McCallc316b222019-04-26 07:45:49 +0000729 while (!Lex.LexFromRawLexer(Tok))
730 A(Tok);
Kadir Cetinkaya194117f2019-09-25 14:12:05 +0000731 // LexFromRawLexer returns true after it lexes last token, so we still have
732 // one more token to report.
733 A(Tok);
Sam McCallc316b222019-04-26 07:45:49 +0000734}
735
736llvm::StringMap<unsigned> collectIdentifiers(llvm::StringRef Content,
737 const format::FormatStyle &Style) {
Eric Liu00d99bd2019-04-11 09:36:36 +0000738 llvm::StringMap<unsigned> Identifiers;
Sam McCallc316b222019-04-26 07:45:49 +0000739 lex(Content, Style, [&](const clang::Token &Tok) {
Eric Liu00d99bd2019-04-11 09:36:36 +0000740 switch (Tok.getKind()) {
741 case tok::identifier:
742 ++Identifiers[Tok.getIdentifierInfo()->getName()];
743 break;
744 case tok::raw_identifier:
745 ++Identifiers[Tok.getRawIdentifier()];
746 break;
747 default:
Sam McCallc316b222019-04-26 07:45:49 +0000748 break;
Eric Liu00d99bd2019-04-11 09:36:36 +0000749 }
Sam McCallc316b222019-04-26 07:45:49 +0000750 });
Eric Liu00d99bd2019-04-11 09:36:36 +0000751 return Identifiers;
752}
753
Sam McCallc316b222019-04-26 07:45:49 +0000754namespace {
755enum NamespaceEvent {
756 BeginNamespace, // namespace <ns> {. Payload is resolved <ns>.
757 EndNamespace, // } // namespace <ns>. Payload is resolved *outer* namespace.
758 UsingDirective // using namespace <ns>. Payload is unresolved <ns>.
759};
760// Scans C++ source code for constructs that change the visible namespaces.
761void parseNamespaceEvents(
762 llvm::StringRef Code, const format::FormatStyle &Style,
763 llvm::function_ref<void(NamespaceEvent, llvm::StringRef)> Callback) {
764
765 // Stack of enclosing namespaces, e.g. {"clang", "clangd"}
766 std::vector<std::string> Enclosing; // Contains e.g. "clang", "clangd"
767 // Stack counts open braces. true if the brace opened a namespace.
768 std::vector<bool> BraceStack;
769
770 enum {
771 Default,
772 Namespace, // just saw 'namespace'
773 NamespaceName, // just saw 'namespace' NSName
774 Using, // just saw 'using'
775 UsingNamespace, // just saw 'using namespace'
776 UsingNamespaceName, // just saw 'using namespace' NSName
777 } State = Default;
778 std::string NSName;
779
780 lex(Code, Style, [&](const clang::Token &Tok) {
781 switch(Tok.getKind()) {
782 case tok::raw_identifier:
783 // In raw mode, this could be a keyword or a name.
784 switch (State) {
785 case UsingNamespace:
786 case UsingNamespaceName:
787 NSName.append(Tok.getRawIdentifier());
788 State = UsingNamespaceName;
789 break;
790 case Namespace:
791 case NamespaceName:
792 NSName.append(Tok.getRawIdentifier());
793 State = NamespaceName;
794 break;
795 case Using:
796 State =
797 (Tok.getRawIdentifier() == "namespace") ? UsingNamespace : Default;
798 break;
799 case Default:
800 NSName.clear();
801 if (Tok.getRawIdentifier() == "namespace")
802 State = Namespace;
803 else if (Tok.getRawIdentifier() == "using")
804 State = Using;
805 break;
806 }
807 break;
808 case tok::coloncolon:
809 // This can come at the beginning or in the middle of a namespace name.
810 switch (State) {
811 case UsingNamespace:
812 case UsingNamespaceName:
813 NSName.append("::");
814 State = UsingNamespaceName;
815 break;
816 case NamespaceName:
817 NSName.append("::");
818 State = NamespaceName;
819 break;
820 case Namespace: // Not legal here.
821 case Using:
822 case Default:
823 State = Default;
824 break;
825 }
826 break;
827 case tok::l_brace:
828 // Record which { started a namespace, so we know when } ends one.
829 if (State == NamespaceName) {
830 // Parsed: namespace <name> {
831 BraceStack.push_back(true);
832 Enclosing.push_back(NSName);
833 Callback(BeginNamespace, llvm::join(Enclosing, "::"));
834 } else {
835 // This case includes anonymous namespaces (State = Namespace).
836 // For our purposes, they're not namespaces and we ignore them.
837 BraceStack.push_back(false);
838 }
839 State = Default;
840 break;
841 case tok::r_brace:
842 // If braces are unmatched, we're going to be confused, but don't crash.
843 if (!BraceStack.empty()) {
844 if (BraceStack.back()) {
845 // Parsed: } // namespace
846 Enclosing.pop_back();
847 Callback(EndNamespace, llvm::join(Enclosing, "::"));
848 }
849 BraceStack.pop_back();
850 }
851 break;
852 case tok::semi:
853 if (State == UsingNamespaceName)
854 // Parsed: using namespace <name> ;
855 Callback(UsingDirective, llvm::StringRef(NSName));
856 State = Default;
857 break;
858 default:
859 State = Default;
860 break;
861 }
862 });
863}
864
865// Returns the prefix namespaces of NS: {"" ... NS}.
866llvm::SmallVector<llvm::StringRef, 8> ancestorNamespaces(llvm::StringRef NS) {
867 llvm::SmallVector<llvm::StringRef, 8> Results;
868 Results.push_back(NS.take_front(0));
869 NS.split(Results, "::", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
870 for (llvm::StringRef &R : Results)
871 R = NS.take_front(R.end() - NS.begin());
872 return Results;
873}
874
875} // namespace
876
877std::vector<std::string> visibleNamespaces(llvm::StringRef Code,
878 const format::FormatStyle &Style) {
879 std::string Current;
880 // Map from namespace to (resolved) namespaces introduced via using directive.
881 llvm::StringMap<llvm::StringSet<>> UsingDirectives;
882
883 parseNamespaceEvents(Code, Style,
884 [&](NamespaceEvent Event, llvm::StringRef NS) {
885 switch (Event) {
886 case BeginNamespace:
887 case EndNamespace:
888 Current = NS;
889 break;
890 case UsingDirective:
891 if (NS.consume_front("::"))
892 UsingDirectives[Current].insert(NS);
893 else {
894 for (llvm::StringRef Enclosing :
895 ancestorNamespaces(Current)) {
896 if (Enclosing.empty())
897 UsingDirectives[Current].insert(NS);
898 else
899 UsingDirectives[Current].insert(
900 (Enclosing + "::" + NS).str());
901 }
902 }
903 break;
904 }
905 });
906
907 std::vector<std::string> Found;
908 for (llvm::StringRef Enclosing : ancestorNamespaces(Current)) {
909 Found.push_back(Enclosing);
910 auto It = UsingDirectives.find(Enclosing);
911 if (It != UsingDirectives.end())
912 for (const auto& Used : It->second)
913 Found.push_back(Used.getKey());
914 }
915
Sam McCallc316b222019-04-26 07:45:49 +0000916 llvm::sort(Found, [&](const std::string &LHS, const std::string &RHS) {
917 if (Current == RHS)
918 return false;
919 if (Current == LHS)
920 return true;
921 return LHS < RHS;
922 });
923 Found.erase(std::unique(Found.begin(), Found.end()), Found.end());
924 return Found;
925}
926
Sam McCall9fb22b22019-05-06 10:25:10 +0000927llvm::StringSet<> collectWords(llvm::StringRef Content) {
928 // We assume short words are not significant.
929 // We may want to consider other stopwords, e.g. language keywords.
930 // (A very naive implementation showed no benefit, but lexing might do better)
931 static constexpr int MinWordLength = 4;
932
933 std::vector<CharRole> Roles(Content.size());
934 calculateRoles(Content, Roles);
935
936 llvm::StringSet<> Result;
937 llvm::SmallString<256> Word;
938 auto Flush = [&] {
939 if (Word.size() >= MinWordLength) {
940 for (char &C : Word)
941 C = llvm::toLower(C);
942 Result.insert(Word);
943 }
944 Word.clear();
945 };
946 for (unsigned I = 0; I < Content.size(); ++I) {
947 switch (Roles[I]) {
948 case Head:
949 Flush();
950 LLVM_FALLTHROUGH;
951 case Tail:
952 Word.push_back(Content[I]);
953 break;
954 case Unknown:
955 case Separator:
956 Flush();
957 break;
958 }
959 }
960 Flush();
961
962 return Result;
963}
964
Haojian Wu9d34f452019-07-01 09:26:48 +0000965llvm::Optional<DefinedMacro> locateMacroAt(SourceLocation Loc,
966 Preprocessor &PP) {
967 const auto &SM = PP.getSourceManager();
968 const auto &LangOpts = PP.getLangOpts();
969 Token Result;
970 if (Lexer::getRawToken(SM.getSpellingLoc(Loc), Result, SM, LangOpts, false))
971 return None;
972 if (Result.is(tok::raw_identifier))
973 PP.LookUpIdentifierInfo(Result);
974 IdentifierInfo *IdentifierInfo = Result.getIdentifierInfo();
975 if (!IdentifierInfo || !IdentifierInfo->hadMacroDefinition())
976 return None;
977
978 std::pair<FileID, unsigned int> DecLoc = SM.getDecomposedExpansionLoc(Loc);
979 // Get the definition just before the searched location so that a macro
980 // referenced in a '#undef MACRO' can still be found.
981 SourceLocation BeforeSearchedLocation =
982 SM.getMacroArgExpandedLocation(SM.getLocForStartOfFile(DecLoc.first)
983 .getLocWithOffset(DecLoc.second - 1));
984 MacroDefinition MacroDef =
985 PP.getMacroDefinitionAtLoc(IdentifierInfo, BeforeSearchedLocation);
986 if (auto *MI = MacroDef.getMacroInfo())
987 return DefinedMacro{IdentifierInfo->getName(), MI};
988 return None;
989}
990
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000991llvm::Expected<std::string> Edit::apply() const {
992 return tooling::applyAllReplacements(InitialCode, Replacements);
993}
994
995std::vector<TextEdit> Edit::asTextEdits() const {
996 return replacementsToEdits(InitialCode, Replacements);
997}
998
999bool Edit::canApplyTo(llvm::StringRef Code) const {
1000 // Create line iterators, since line numbers are important while applying our
1001 // edit we cannot skip blank lines.
1002 auto LHS = llvm::MemoryBuffer::getMemBuffer(Code);
1003 llvm::line_iterator LHSIt(*LHS, /*SkipBlanks=*/false);
1004
1005 auto RHS = llvm::MemoryBuffer::getMemBuffer(InitialCode);
1006 llvm::line_iterator RHSIt(*RHS, /*SkipBlanks=*/false);
1007
1008 // Compare the InitialCode we prepared the edit for with the Code we received
1009 // line by line to make sure there are no differences.
1010 // FIXME: This check is too conservative now, it should be enough to only
1011 // check lines around the replacements contained inside the Edit.
1012 while (!LHSIt.is_at_eof() && !RHSIt.is_at_eof()) {
1013 if (*LHSIt != *RHSIt)
1014 return false;
1015 ++LHSIt;
1016 ++RHSIt;
1017 }
1018
1019 // After we reach EOF for any of the files we make sure the other one doesn't
1020 // contain any additional content except empty lines, they should not
1021 // interfere with the edit we produced.
1022 while (!LHSIt.is_at_eof()) {
1023 if (!LHSIt->empty())
1024 return false;
1025 ++LHSIt;
1026 }
1027 while (!RHSIt.is_at_eof()) {
1028 if (!RHSIt->empty())
1029 return false;
1030 ++RHSIt;
1031 }
1032 return true;
1033}
1034
1035llvm::Error reformatEdit(Edit &E, const format::FormatStyle &Style) {
1036 if (auto NewEdits = cleanupAndFormat(E.InitialCode, E.Replacements, Style))
1037 E.Replacements = std::move(*NewEdits);
1038 else
1039 return NewEdits.takeError();
1040 return llvm::Error::success();
1041}
1042
Sam McCallb536a2a2017-12-19 12:23:48 +00001043} // namespace clangd
1044} // namespace clang