blob: b36d11d64a3eb56c992775b8522bcb18d2f0802f [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"
Haojian Wu509efe52019-11-13 16:30:07 +010020#include "clang/Driver/Types.h"
Sam McCallc316b222019-04-26 07:45:49 +000021#include "clang/Format/Format.h"
Marc-Andre Laperle1be69702018-07-05 19:35:01 +000022#include "clang/Lex/Lexer.h"
Haojian Wu9d34f452019-07-01 09:26:48 +000023#include "clang/Lex/Preprocessor.h"
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +020024#include "clang/Lex/Token.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000025#include "clang/Tooling/Core/Replacement.h"
26#include "llvm/ADT/ArrayRef.h"
Ilya Biryukov43998782019-01-31 21:30:05 +000027#include "llvm/ADT/None.h"
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +020028#include "llvm/ADT/STLExtras.h"
Sam McCallc316b222019-04-26 07:45:49 +000029#include "llvm/ADT/StringExtras.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000030#include "llvm/ADT/StringMap.h"
Ilya Biryukov43998782019-01-31 21:30:05 +000031#include "llvm/ADT/StringRef.h"
Sam McCall9fb22b22019-05-06 10:25:10 +000032#include "llvm/Support/Compiler.h"
Simon Marchi766338a2018-03-21 14:36:46 +000033#include "llvm/Support/Errc.h"
34#include "llvm/Support/Error.h"
Sam McCall8b25d222019-03-28 14:37:51 +000035#include "llvm/Support/ErrorHandling.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000036#include "llvm/Support/LineIterator.h"
37#include "llvm/Support/MemoryBuffer.h"
Marc-Andre Laperle1be69702018-07-05 19:35:01 +000038#include "llvm/Support/Path.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000039#include "llvm/Support/SHA1.h"
40#include "llvm/Support/VirtualFileSystem.h"
Sam McCall674d8a92019-07-08 11:33:17 +000041#include "llvm/Support/xxhash.h"
Sam McCallc316b222019-04-26 07:45:49 +000042#include <algorithm>
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +020043#include <cstddef>
44#include <string>
45#include <vector>
Marc-Andre Laperle63a10982018-02-21 02:39:08 +000046
Sam McCallb536a2a2017-12-19 12:23:48 +000047namespace clang {
48namespace clangd {
Sam McCallb536a2a2017-12-19 12:23:48 +000049
Sam McCalla4962cc2018-04-27 11:59:28 +000050// 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.
56template <typename Callback>
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000057static bool iterateCodepoints(llvm::StringRef U8, const Callback &CB) {
Sam McCall8b25d222019-03-28 14:37:51 +000058 // 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.
Sam McCalla4962cc2018-04-27 11:59:28 +000060 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.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000069 size_t UTF8Length = llvm::countLeadingOnes(C);
Sam McCalla4962cc2018-04-27 11:59:28 +000070 // 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
Sam McCall8b25d222019-03-28 14:37:51 +000083// 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.
87static size_t measureUnits(llvm::StringRef U8, int Units, OffsetEncoding Enc,
88 bool &Valid) {
89 Valid = Units >= 0;
90 if (Units <= 0)
91 return 0;
Sam McCalla4962cc2018-04-27 11:59:28 +000092 size_t Result = 0;
Sam McCall8b25d222019-03-28 14:37:51 +000093 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 }
Sam McCalla4962cc2018-04-27 11:59:28 +0000116 // Don't return an out-of-range index if we overran.
Sam McCall8b25d222019-03-28 14:37:51 +0000117 if (Result > U8.size()) {
118 Valid = false;
119 return U8.size();
120 }
121 return Result;
Sam McCalla4962cc2018-04-27 11:59:28 +0000122}
123
Sam McCalla69698f2019-03-27 17:47:49 +0000124Key<OffsetEncoding> kCurrentOffsetEncoding;
Sam McCall8b25d222019-03-28 14:37:51 +0000125static OffsetEncoding lspEncoding() {
Sam McCalla69698f2019-03-27 17:47:49 +0000126 auto *Enc = Context::current().get(kCurrentOffsetEncoding);
Sam McCall8b25d222019-03-28 14:37:51 +0000127 return Enc ? *Enc : OffsetEncoding::UTF16;
Sam McCalla69698f2019-03-27 17:47:49 +0000128}
129
Sam McCalla4962cc2018-04-27 11:59:28 +0000130// Like most strings in clangd, the input is UTF-8 encoded.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000131size_t lspLength(llvm::StringRef Code) {
Sam McCalla4962cc2018-04-27 11:59:28 +0000132 size_t Count = 0;
Sam McCall8b25d222019-03-28 14:37:51 +0000133 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 }
Sam McCalla4962cc2018-04-27 11:59:28 +0000152 return Count;
153}
154
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000155llvm::Expected<size_t> positionToOffset(llvm::StringRef Code, Position P,
156 bool AllowColumnsBeyondLineLength) {
Sam McCallb536a2a2017-12-19 12:23:48 +0000157 if (P.line < 0)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000158 return llvm::make_error<llvm::StringError>(
159 llvm::formatv("Line value can't be negative ({0})", P.line),
160 llvm::errc::invalid_argument);
Simon Marchi766338a2018-03-21 14:36:46 +0000161 if (P.character < 0)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000162 return llvm::make_error<llvm::StringError>(
163 llvm::formatv("Character value can't be negative ({0})", P.character),
164 llvm::errc::invalid_argument);
Sam McCallb536a2a2017-12-19 12:23:48 +0000165 size_t StartOfLine = 0;
166 for (int I = 0; I != P.line; ++I) {
167 size_t NextNL = Code.find('\n', StartOfLine);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000168 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);
Sam McCallb536a2a2017-12-19 12:23:48 +0000172 StartOfLine = NextNL + 1;
173 }
Sam McCalla69698f2019-03-27 17:47:49 +0000174 StringRef Line =
175 Code.substr(StartOfLine).take_until([](char C) { return C == '\n'; });
Simon Marchi766338a2018-03-21 14:36:46 +0000176
Sam McCall8b25d222019-03-28 14:37:51 +0000177 // P.character may be in UTF-16, transcode if necessary.
Sam McCalla4962cc2018-04-27 11:59:28 +0000178 bool Valid;
Sam McCall8b25d222019-03-28 14:37:51 +0000179 size_t ByteInLine = measureUnits(Line, P.character, lspEncoding(), Valid);
Sam McCalla4962cc2018-04-27 11:59:28 +0000180 if (!Valid && !AllowColumnsBeyondLineLength)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000181 return llvm::make_error<llvm::StringError>(
Sam McCall8b25d222019-03-28 14:37:51 +0000182 llvm::formatv("{0} offset {1} is invalid for line {2}", lspEncoding(),
183 P.character, P.line),
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000184 llvm::errc::invalid_argument);
Sam McCall8b25d222019-03-28 14:37:51 +0000185 return StartOfLine + ByteInLine;
Sam McCallb536a2a2017-12-19 12:23:48 +0000186}
187
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000188Position offsetToPosition(llvm::StringRef Code, size_t Offset) {
Sam McCallb536a2a2017-12-19 12:23:48 +0000189 Offset = std::min(Code.size(), Offset);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000190 llvm::StringRef Before = Code.substr(0, Offset);
Sam McCallb536a2a2017-12-19 12:23:48 +0000191 int Lines = Before.count('\n');
192 size_t PrevNL = Before.rfind('\n');
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000193 size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
Ilya Biryukov7beea3a2018-02-14 10:52:04 +0000194 Position Pos;
195 Pos.line = Lines;
Sam McCall71891122018-10-23 11:51:53 +0000196 Pos.character = lspLength(Before.substr(StartOfLine));
Ilya Biryukov7beea3a2018-02-14 10:52:04 +0000197 return Pos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000198}
199
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000200Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc) {
Sam McCalla4962cc2018-04-27 11:59:28 +0000201 // 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);
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000205 Position P;
Sam McCalla4962cc2018-04-27 11:59:28 +0000206 P.line = static_cast<int>(SM.getLineNumber(FID, Offset)) - 1;
207 bool Invalid = false;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000208 llvm::StringRef Code = SM.getBufferData(FID, &Invalid);
Sam McCalla4962cc2018-04-27 11:59:28 +0000209 if (!Invalid) {
210 auto ColumnInBytes = SM.getColumnNumber(FID, Offset) - 1;
211 auto LineSoFar = Code.substr(Offset - ColumnInBytes, ColumnInBytes);
Sam McCall71891122018-10-23 11:51:53 +0000212 P.character = lspLength(LineSoFar);
Sam McCalla4962cc2018-04-27 11:59:28 +0000213 }
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000214 return P;
215}
216
Sam McCall95738072019-08-06 20:25:59 +0000217bool 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
227SourceLocation 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
Haojian Wu92c32572019-06-25 08:01:46 +0000235llvm::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
Haojian Wu9f2bf662019-10-01 11:03:56 +0000246namespace {
247
248enum TokenFlavor { Identifier, Operator, Whitespace, Other };
249
250bool 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
264TokenFlavor 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
Sam McCall19cefc22019-09-03 15:34:47 +0000285SourceLocation 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
Haojian Wu9f2bf662019-10-01 11:03:56 +0000295 // 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.
Sam McCall19cefc22019-09-03 15:34:47 +0000305 SourceLocation InputLoc = SM.getComposedLoc(FID, *Offset);
Haojian Wu9f2bf662019-10-01 11:03:56 +0000306 if (*Offset == 0) // Case 1 or 4.
Sam McCallb2a984c02019-09-04 10:15:27 +0000307 return InputLoc;
Sam McCall19cefc22019-09-03 15:34:47 +0000308 SourceLocation Before = SM.getComposedLoc(FID, *Offset - 1);
Haojian Wu9f2bf662019-10-01 11:03:56 +0000309 SourceLocation BeforeTokBeginning =
310 Lexer::GetBeginningOfToken(Before, SM, LangOpts);
311 TokenFlavor BeforeKind = getTokenFlavor(BeforeTokBeginning, SM, LangOpts);
Sam McCall19cefc22019-09-03 15:34:47 +0000312
Haojian Wu9f2bf662019-10-01 11:03:56 +0000313 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;
Sam McCall19cefc22019-09-03 15:34:47 +0000346}
347
Ilya Biryukov43998782019-01-31 21:30:05 +0000348bool 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
363bool 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
378bool halfOpenRangeTouches(const SourceManager &Mgr, SourceRange R,
379 SourceLocation L) {
380 return L == R.getEnd() || halfOpenRangeContains(Mgr, R, L);
381}
382
Sam McCallc791d852019-08-27 08:44:06 +0000383SourceLocation 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
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000405static 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
421static 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
429static 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.
437static 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.
446static SourceRange unionTokenRange(SourceRange R1, SourceRange R2,
447 const SourceManager &SM,
448 const LangOptions &LangOpts) {
Sam McCallc791d852019-08-27 08:44:06 +0000449 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);
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000459}
460
Sam McCallc791d852019-08-27 08:44:06 +0000461// 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.
464static 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();
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000492}
493
494// Find an expansion range (not necessarily immediate) the ends of which are in
495// the same file id.
496static SourceRange
497getExpansionTokenRangeInSameFile(SourceLocation Loc, const SourceManager &SM,
498 const LangOptions &LangOpts) {
Sam McCallc791d852019-08-27 08:44:06 +0000499 return rangeInCommonFile(
500 toTokenRange(SM.getImmediateExpansionRange(Loc), SM, LangOpts), SM,
501 LangOpts);
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000502}
Sam McCallc791d852019-08-27 08:44:06 +0000503
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000504// Returns the file range for a given Location as a Token Range
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000505// 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.
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000510// - We want to split '>>' tokens as the lexer parses the '>>' in nested
511// template instantiations as a '>>' instead of two '>'s.
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000512// There is also getExpansionRange but it simply calls
513// getImmediateExpansionRange on the begin and ends separately which is wrong.
514static SourceRange getTokenFileRange(SourceLocation Loc,
515 const SourceManager &SM,
516 const LangOptions &LangOpts) {
517 SourceRange FileRange = Loc;
518 while (!FileRange.getBegin().isFileID()) {
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000519 if (SM.isMacroArgExpansion(FileRange.getBegin())) {
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000520 FileRange = unionTokenRange(
521 SM.getImmediateSpellingLoc(FileRange.getBegin()),
522 SM.getImmediateSpellingLoc(FileRange.getEnd()), SM, LangOpts);
Sam McCallc791d852019-08-27 08:44:06 +0000523 assert(SM.isWrittenInSameFile(FileRange.getBegin(), FileRange.getEnd()));
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000524 } else {
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000525 SourceRange ExpansionRangeForBegin =
526 getExpansionTokenRangeInSameFile(FileRange.getBegin(), SM, LangOpts);
527 SourceRange ExpansionRangeForEnd =
528 getExpansionTokenRangeInSameFile(FileRange.getEnd(), SM, LangOpts);
Sam McCallc791d852019-08-27 08:44:06 +0000529 if (ExpansionRangeForBegin.isInvalid() ||
530 ExpansionRangeForEnd.isInvalid())
531 return SourceRange();
532 assert(SM.isWrittenInSameFile(ExpansionRangeForBegin.getBegin(),
533 ExpansionRangeForEnd.getBegin()) &&
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000534 "Both Expansion ranges should be in same file.");
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000535 FileRange = unionTokenRange(ExpansionRangeForBegin, ExpansionRangeForEnd,
536 SM, LangOpts);
537 }
538 }
539 return FileRange;
540}
541
Haojian Wu6ae86ea2019-07-19 08:33:39 +0000542bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM) {
543 return Loc.isValid() && SM.isWrittenInMainFile(SM.getExpansionLoc(Loc));
544}
545
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000546llvm::Optional<SourceRange> toHalfOpenFileRange(const SourceManager &SM,
Ilya Biryukov43998782019-01-31 21:30:05 +0000547 const LangOptions &LangOpts,
548 SourceRange R) {
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000549 SourceRange R1 = getTokenFileRange(R.getBegin(), SM, LangOpts);
550 if (!isValidFileRange(SM, R1))
Ilya Biryukov43998782019-01-31 21:30:05 +0000551 return llvm::None;
Ilya Biryukov43998782019-01-31 21:30:05 +0000552
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000553 SourceRange R2 = getTokenFileRange(R.getEnd(), SM, LangOpts);
554 if (!isValidFileRange(SM, R2))
Ilya Biryukov43998782019-01-31 21:30:05 +0000555 return llvm::None;
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000556
Sam McCallc791d852019-08-27 08:44:06 +0000557 SourceRange Result =
558 rangeInCommonFile(unionTokenRange(R1, R2, SM, LangOpts), SM, LangOpts);
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000559 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
Ilya Biryukov43998782019-01-31 21:30:05 +0000565 return Result;
566}
567
568llvm::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
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000579llvm::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
Ilya Biryukov71028b82018-03-12 15:28:22 +0000589Range 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
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000597std::pair<size_t, size_t> offsetToClangLineColumn(llvm::StringRef Code,
Sam McCalla4962cc2018-04-27 11:59:28 +0000598 size_t Offset) {
599 Offset = std::min(Code.size(), Offset);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000600 llvm::StringRef Before = Code.substr(0, Offset);
Sam McCalla4962cc2018-04-27 11:59:28 +0000601 int Lines = Before.count('\n');
602 size_t PrevNL = Before.rfind('\n');
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000603 size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
Sam McCalla4962cc2018-04-27 11:59:28 +0000604 return {Lines + 1, Offset - StartOfLine + 1};
605}
606
Ilya Biryukov43998782019-01-31 21:30:05 +0000607std::pair<StringRef, StringRef> splitQualifiedName(StringRef QName) {
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000608 size_t Pos = QName.rfind("::");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000609 if (Pos == llvm::StringRef::npos)
610 return {llvm::StringRef(), QName};
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000611 return {QName.substr(0, Pos + 2), QName.substr(Pos + 2)};
612}
613
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000614TextEdit replacementToEdit(llvm::StringRef Code,
615 const tooling::Replacement &R) {
Eric Liu9133ecd2018-05-11 12:12:08 +0000616 Range ReplacementRange = {
617 offsetToPosition(Code, R.getOffset()),
618 offsetToPosition(Code, R.getOffset() + R.getLength())};
619 return {ReplacementRange, R.getReplacementText()};
620}
621
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000622std::vector<TextEdit> replacementsToEdits(llvm::StringRef Code,
Eric Liu9133ecd2018-05-11 12:12:08 +0000623 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
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000630llvm::Optional<std::string> getCanonicalPath(const FileEntry *F,
631 const SourceManager &SourceMgr) {
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000632 if (!F)
633 return None;
Simon Marchi25f1f732018-08-10 22:27:53 +0000634
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000635 llvm::SmallString<128> FilePath = F->getName();
636 if (!llvm::sys::path::is_absolute(FilePath)) {
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000637 if (auto EC =
Duncan P. N. Exon Smithdb8a7422019-03-26 22:32:06 +0000638 SourceMgr.getFileManager().getVirtualFileSystem().makeAbsolute(
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000639 FilePath)) {
640 elog("Could not turn relative path '{0}' to absolute: {1}", FilePath,
641 EC.message());
Sam McCallc008af62018-10-20 15:30:37 +0000642 return None;
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000643 }
644 }
Simon Marchi25f1f732018-08-10 22:27:53 +0000645
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000646 // Handle the symbolic link path case where the current working directory
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000647 // (getCurrentWorkingDirectory) is a symlink. We always want to the real
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000648 // 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"
Harlan Haskinsa02f8572019-08-01 21:32:01 +0000657 if (auto Dir = SourceMgr.getFileManager().getDirectory(
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000658 llvm::sys::path::parent_path(FilePath))) {
659 llvm::SmallString<128> RealPath;
Harlan Haskinsa02f8572019-08-01 21:32:01 +0000660 llvm::StringRef DirName = SourceMgr.getFileManager().getCanonicalName(*Dir);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000661 llvm::sys::path::append(RealPath, DirName,
662 llvm::sys::path::filename(FilePath));
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000663 return RealPath.str().str();
Simon Marchi25f1f732018-08-10 22:27:53 +0000664 }
665
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000666 return FilePath.str().str();
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000667}
668
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +0000669TextEdit 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
Haojian Wuaa3ed5a2019-01-25 15:14:03 +0000678bool isRangeConsecutive(const Range &Left, const Range &Right) {
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +0000679 return Left.end.line == Right.start.line &&
680 Left.end.character == Right.start.character;
681}
682
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000683FileDigest digest(llvm::StringRef Content) {
Sam McCall674d8a92019-07-08 11:33:17 +0000684 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;
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000691}
692
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000693llvm::Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID) {
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000694 bool Invalid = false;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000695 llvm::StringRef Content = SM.getBufferData(FID, &Invalid);
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000696 if (Invalid)
697 return None;
698 return digest(Content);
699}
700
Eric Liudd662772019-01-28 14:01:55 +0000701format::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
Haojian Wu12e194c2019-02-06 15:24:50 +0000714llvm::Expected<tooling::Replacements>
715cleanupAndFormat(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
Haojian Wuc5e4cf42019-11-07 10:53:19 +0100723static void
724lex(llvm::StringRef Code, const LangOptions &LangOpts,
725 llvm::function_ref<void(const clang::Token &, const SourceManager &SM)>
726 Action) {
Sam McCallc316b222019-04-26 07:45:49 +0000727 // FIXME: InMemoryFileAdapter crashes unless the buffer is null terminated!
728 std::string NullTerminatedCode = Code.str();
729 SourceManagerForFile FileSM("dummy.cpp", NullTerminatedCode);
Eric Liu00d99bd2019-04-11 09:36:36 +0000730 auto &SM = FileSM.get();
731 auto FID = SM.getMainFileID();
Haojian Wu7ea4c6f2019-10-30 13:21:47 +0100732 // Create a raw lexer (with no associated preprocessor object).
733 Lexer Lex(FID, SM.getBuffer(FID), SM, LangOpts);
Eric Liu00d99bd2019-04-11 09:36:36 +0000734 Token Tok;
735
Sam McCallc316b222019-04-26 07:45:49 +0000736 while (!Lex.LexFromRawLexer(Tok))
Haojian Wu7ea4c6f2019-10-30 13:21:47 +0100737 Action(Tok, SM);
Kadir Cetinkaya194117f2019-09-25 14:12:05 +0000738 // LexFromRawLexer returns true after it lexes last token, so we still have
739 // one more token to report.
Haojian Wu7ea4c6f2019-10-30 13:21:47 +0100740 Action(Tok, SM);
Sam McCallc316b222019-04-26 07:45:49 +0000741}
742
743llvm::StringMap<unsigned> collectIdentifiers(llvm::StringRef Content,
744 const format::FormatStyle &Style) {
Eric Liu00d99bd2019-04-11 09:36:36 +0000745 llvm::StringMap<unsigned> Identifiers;
Haojian Wu7ea4c6f2019-10-30 13:21:47 +0100746 auto LangOpt = format::getFormattingLangOpts(Style);
747 lex(Content, LangOpt, [&](const clang::Token &Tok, const SourceManager &) {
748 if (Tok.getKind() == tok::raw_identifier)
Eric Liu00d99bd2019-04-11 09:36:36 +0000749 ++Identifiers[Tok.getRawIdentifier()];
Sam McCallc316b222019-04-26 07:45:49 +0000750 });
Eric Liu00d99bd2019-04-11 09:36:36 +0000751 return Identifiers;
752}
753
Haojian Wu7ea4c6f2019-10-30 13:21:47 +0100754std::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
Sam McCallc316b222019-04-26 07:45:49 +0000771namespace {
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +0200772struct 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;
Sam McCallc316b222019-04-26 07:45:49 +0000781};
782// Scans C++ source code for constructs that change the visible namespaces.
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +0200783void parseNamespaceEvents(llvm::StringRef Code,
784 const format::FormatStyle &Style,
785 llvm::function_ref<void(NamespaceEvent)> Callback) {
Sam McCallc316b222019-04-26 07:45:49 +0000786
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
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +0200802 NamespaceEvent Event;
Haojian Wu7ea4c6f2019-10-30 13:21:47 +0100803 lex(Code, format::getFormattingLangOpts(Style),
804 [&](const clang::Token &Tok,const SourceManager &SM) {
805 Event.Pos = sourceLocToPosition(SM, Tok.getLocation());
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +0200806 switch (Tok.getKind()) {
Sam McCallc316b222019-04-26 07:45:49 +0000807 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);
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +0200858 Event.Trigger = NamespaceEvent::BeginNamespace;
859 Event.Payload = llvm::join(Enclosing, "::");
860 Callback(Event);
Sam McCallc316b222019-04-26 07:45:49 +0000861 } 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();
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +0200874 Event.Trigger = NamespaceEvent::EndNamespace;
875 Event.Payload = llvm::join(Enclosing, "::");
876 Callback(Event);
Sam McCallc316b222019-04-26 07:45:49 +0000877 }
878 BraceStack.pop_back();
879 }
880 break;
881 case tok::semi:
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +0200882 if (State == UsingNamespaceName) {
Sam McCallc316b222019-04-26 07:45:49 +0000883 // Parsed: using namespace <name> ;
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +0200884 Event.Trigger = NamespaceEvent::UsingDirective;
885 Event.Payload = std::move(NSName);
886 Callback(Event);
887 }
Sam McCallc316b222019-04-26 07:45:49 +0000888 State = Default;
889 break;
890 default:
891 State = Default;
892 break;
893 }
894 });
895}
896
897// Returns the prefix namespaces of NS: {"" ... NS}.
898llvm::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
909std::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
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +0200915 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 });
Sam McCallc316b222019-04-26 07:45:49 +0000936
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())
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +0200942 for (const auto &Used : It->second)
Sam McCallc316b222019-04-26 07:45:49 +0000943 Found.push_back(Used.getKey());
944 }
945
Sam McCallc316b222019-04-26 07:45:49 +0000946 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
Sam McCall9fb22b22019-05-06 10:25:10 +0000957llvm::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
Haojian Wu9d34f452019-07-01 09:26:48 +0000995llvm::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
Kadir Cetinkaya5b270932019-09-09 12:28:44 +00001021llvm::Expected<std::string> Edit::apply() const {
1022 return tooling::applyAllReplacements(InitialCode, Replacements);
1023}
1024
1025std::vector<TextEdit> Edit::asTextEdits() const {
1026 return replacementsToEdits(InitialCode, Replacements);
1027}
1028
1029bool 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
1065llvm::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
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +02001073EligibleRegion 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
Haojian Wu509efe52019-11-13 16:30:07 +01001126bool 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
Sam McCallb536a2a2017-12-19 12:23:48 +00001138} // namespace clangd
1139} // namespace clang