blob: d505645a74f658374e703f1f0a209dcf2da44a9f [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 Cetinkayad62e3ed2019-09-25 11:35:38 +020023#include "clang/Lex/Token.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000024#include "clang/Tooling/Core/Replacement.h"
25#include "llvm/ADT/ArrayRef.h"
Ilya Biryukov43998782019-01-31 21:30:05 +000026#include "llvm/ADT/None.h"
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +020027#include "llvm/ADT/STLExtras.h"
Sam McCallc316b222019-04-26 07:45:49 +000028#include "llvm/ADT/StringExtras.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000029#include "llvm/ADT/StringMap.h"
Ilya Biryukov43998782019-01-31 21:30:05 +000030#include "llvm/ADT/StringRef.h"
Sam McCall9fb22b22019-05-06 10:25:10 +000031#include "llvm/Support/Compiler.h"
Simon Marchi766338a2018-03-21 14:36:46 +000032#include "llvm/Support/Errc.h"
33#include "llvm/Support/Error.h"
Sam McCall8b25d222019-03-28 14:37:51 +000034#include "llvm/Support/ErrorHandling.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000035#include "llvm/Support/LineIterator.h"
36#include "llvm/Support/MemoryBuffer.h"
Marc-Andre Laperle1be69702018-07-05 19:35:01 +000037#include "llvm/Support/Path.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000038#include "llvm/Support/SHA1.h"
39#include "llvm/Support/VirtualFileSystem.h"
Sam McCall674d8a92019-07-08 11:33:17 +000040#include "llvm/Support/xxhash.h"
Sam McCallc316b222019-04-26 07:45:49 +000041#include <algorithm>
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +020042#include <cstddef>
43#include <string>
44#include <vector>
Marc-Andre Laperle63a10982018-02-21 02:39:08 +000045
Sam McCallb536a2a2017-12-19 12:23:48 +000046namespace clang {
47namespace clangd {
Sam McCallb536a2a2017-12-19 12:23:48 +000048
Sam McCalla4962cc2018-04-27 11:59:28 +000049// Here be dragons. LSP positions use columns measured in *UTF-16 code units*!
50// Clangd uses UTF-8 and byte-offsets internally, so conversion is nontrivial.
51
52// Iterates over unicode codepoints in the (UTF-8) string. For each,
53// invokes CB(UTF-8 length, UTF-16 length), and breaks if it returns true.
54// Returns true if CB returned true, false if we hit the end of string.
55template <typename Callback>
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000056static bool iterateCodepoints(llvm::StringRef U8, const Callback &CB) {
Sam McCall8b25d222019-03-28 14:37:51 +000057 // A codepoint takes two UTF-16 code unit if it's astral (outside BMP).
58 // Astral codepoints are encoded as 4 bytes in UTF-8, starting with 11110xxx.
Sam McCalla4962cc2018-04-27 11:59:28 +000059 for (size_t I = 0; I < U8.size();) {
60 unsigned char C = static_cast<unsigned char>(U8[I]);
61 if (LLVM_LIKELY(!(C & 0x80))) { // ASCII character.
62 if (CB(1, 1))
63 return true;
64 ++I;
65 continue;
66 }
67 // This convenient property of UTF-8 holds for all non-ASCII characters.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000068 size_t UTF8Length = llvm::countLeadingOnes(C);
Sam McCalla4962cc2018-04-27 11:59:28 +000069 // 0xxx is ASCII, handled above. 10xxx is a trailing byte, invalid here.
70 // 11111xxx is not valid UTF-8 at all. Assert because it's probably our bug.
71 assert((UTF8Length >= 2 && UTF8Length <= 4) &&
72 "Invalid UTF-8, or transcoding bug?");
73 I += UTF8Length; // Skip over all trailing bytes.
74 // A codepoint takes two UTF-16 code unit if it's astral (outside BMP).
75 // Astral codepoints are encoded as 4 bytes in UTF-8 (11110xxx ...)
76 if (CB(UTF8Length, UTF8Length == 4 ? 2 : 1))
77 return true;
78 }
79 return false;
80}
81
Sam McCall8b25d222019-03-28 14:37:51 +000082// Returns the byte offset into the string that is an offset of \p Units in
83// the specified encoding.
84// Conceptually, this converts to the encoding, truncates to CodeUnits,
85// converts back to UTF-8, and returns the length in bytes.
86static size_t measureUnits(llvm::StringRef U8, int Units, OffsetEncoding Enc,
87 bool &Valid) {
88 Valid = Units >= 0;
89 if (Units <= 0)
90 return 0;
Sam McCalla4962cc2018-04-27 11:59:28 +000091 size_t Result = 0;
Sam McCall8b25d222019-03-28 14:37:51 +000092 switch (Enc) {
93 case OffsetEncoding::UTF8:
94 Result = Units;
95 break;
96 case OffsetEncoding::UTF16:
97 Valid = iterateCodepoints(U8, [&](int U8Len, int U16Len) {
98 Result += U8Len;
99 Units -= U16Len;
100 return Units <= 0;
101 });
102 if (Units < 0) // Offset in the middle of a surrogate pair.
103 Valid = false;
104 break;
105 case OffsetEncoding::UTF32:
106 Valid = iterateCodepoints(U8, [&](int U8Len, int U16Len) {
107 Result += U8Len;
108 Units--;
109 return Units <= 0;
110 });
111 break;
112 case OffsetEncoding::UnsupportedEncoding:
113 llvm_unreachable("unsupported encoding");
114 }
Sam McCalla4962cc2018-04-27 11:59:28 +0000115 // Don't return an out-of-range index if we overran.
Sam McCall8b25d222019-03-28 14:37:51 +0000116 if (Result > U8.size()) {
117 Valid = false;
118 return U8.size();
119 }
120 return Result;
Sam McCalla4962cc2018-04-27 11:59:28 +0000121}
122
Sam McCalla69698f2019-03-27 17:47:49 +0000123Key<OffsetEncoding> kCurrentOffsetEncoding;
Sam McCall8b25d222019-03-28 14:37:51 +0000124static OffsetEncoding lspEncoding() {
Sam McCalla69698f2019-03-27 17:47:49 +0000125 auto *Enc = Context::current().get(kCurrentOffsetEncoding);
Sam McCall8b25d222019-03-28 14:37:51 +0000126 return Enc ? *Enc : OffsetEncoding::UTF16;
Sam McCalla69698f2019-03-27 17:47:49 +0000127}
128
Sam McCalla4962cc2018-04-27 11:59:28 +0000129// Like most strings in clangd, the input is UTF-8 encoded.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000130size_t lspLength(llvm::StringRef Code) {
Sam McCalla4962cc2018-04-27 11:59:28 +0000131 size_t Count = 0;
Sam McCall8b25d222019-03-28 14:37:51 +0000132 switch (lspEncoding()) {
133 case OffsetEncoding::UTF8:
134 Count = Code.size();
135 break;
136 case OffsetEncoding::UTF16:
137 iterateCodepoints(Code, [&](int U8Len, int U16Len) {
138 Count += U16Len;
139 return false;
140 });
141 break;
142 case OffsetEncoding::UTF32:
143 iterateCodepoints(Code, [&](int U8Len, int U16Len) {
144 ++Count;
145 return false;
146 });
147 break;
148 case OffsetEncoding::UnsupportedEncoding:
149 llvm_unreachable("unsupported encoding");
150 }
Sam McCalla4962cc2018-04-27 11:59:28 +0000151 return Count;
152}
153
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000154llvm::Expected<size_t> positionToOffset(llvm::StringRef Code, Position P,
155 bool AllowColumnsBeyondLineLength) {
Sam McCallb536a2a2017-12-19 12:23:48 +0000156 if (P.line < 0)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000157 return llvm::make_error<llvm::StringError>(
158 llvm::formatv("Line value can't be negative ({0})", P.line),
159 llvm::errc::invalid_argument);
Simon Marchi766338a2018-03-21 14:36:46 +0000160 if (P.character < 0)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000161 return llvm::make_error<llvm::StringError>(
162 llvm::formatv("Character value can't be negative ({0})", P.character),
163 llvm::errc::invalid_argument);
Sam McCallb536a2a2017-12-19 12:23:48 +0000164 size_t StartOfLine = 0;
165 for (int I = 0; I != P.line; ++I) {
166 size_t NextNL = Code.find('\n', StartOfLine);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000167 if (NextNL == llvm::StringRef::npos)
168 return llvm::make_error<llvm::StringError>(
169 llvm::formatv("Line value is out of range ({0})", P.line),
170 llvm::errc::invalid_argument);
Sam McCallb536a2a2017-12-19 12:23:48 +0000171 StartOfLine = NextNL + 1;
172 }
Sam McCalla69698f2019-03-27 17:47:49 +0000173 StringRef Line =
174 Code.substr(StartOfLine).take_until([](char C) { return C == '\n'; });
Simon Marchi766338a2018-03-21 14:36:46 +0000175
Sam McCall8b25d222019-03-28 14:37:51 +0000176 // P.character may be in UTF-16, transcode if necessary.
Sam McCalla4962cc2018-04-27 11:59:28 +0000177 bool Valid;
Sam McCall8b25d222019-03-28 14:37:51 +0000178 size_t ByteInLine = measureUnits(Line, P.character, lspEncoding(), Valid);
Sam McCalla4962cc2018-04-27 11:59:28 +0000179 if (!Valid && !AllowColumnsBeyondLineLength)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000180 return llvm::make_error<llvm::StringError>(
Sam McCall8b25d222019-03-28 14:37:51 +0000181 llvm::formatv("{0} offset {1} is invalid for line {2}", lspEncoding(),
182 P.character, P.line),
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000183 llvm::errc::invalid_argument);
Sam McCall8b25d222019-03-28 14:37:51 +0000184 return StartOfLine + ByteInLine;
Sam McCallb536a2a2017-12-19 12:23:48 +0000185}
186
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000187Position offsetToPosition(llvm::StringRef Code, size_t Offset) {
Sam McCallb536a2a2017-12-19 12:23:48 +0000188 Offset = std::min(Code.size(), Offset);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000189 llvm::StringRef Before = Code.substr(0, Offset);
Sam McCallb536a2a2017-12-19 12:23:48 +0000190 int Lines = Before.count('\n');
191 size_t PrevNL = Before.rfind('\n');
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000192 size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
Ilya Biryukov7beea3a2018-02-14 10:52:04 +0000193 Position Pos;
194 Pos.line = Lines;
Sam McCall71891122018-10-23 11:51:53 +0000195 Pos.character = lspLength(Before.substr(StartOfLine));
Ilya Biryukov7beea3a2018-02-14 10:52:04 +0000196 return Pos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000197}
198
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000199Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc) {
Sam McCalla4962cc2018-04-27 11:59:28 +0000200 // We use the SourceManager's line tables, but its column number is in bytes.
201 FileID FID;
202 unsigned Offset;
203 std::tie(FID, Offset) = SM.getDecomposedSpellingLoc(Loc);
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000204 Position P;
Sam McCalla4962cc2018-04-27 11:59:28 +0000205 P.line = static_cast<int>(SM.getLineNumber(FID, Offset)) - 1;
206 bool Invalid = false;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000207 llvm::StringRef Code = SM.getBufferData(FID, &Invalid);
Sam McCalla4962cc2018-04-27 11:59:28 +0000208 if (!Invalid) {
209 auto ColumnInBytes = SM.getColumnNumber(FID, Offset) - 1;
210 auto LineSoFar = Code.substr(Offset - ColumnInBytes, ColumnInBytes);
Sam McCall71891122018-10-23 11:51:53 +0000211 P.character = lspLength(LineSoFar);
Sam McCalla4962cc2018-04-27 11:59:28 +0000212 }
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000213 return P;
214}
215
Sam McCall95738072019-08-06 20:25:59 +0000216bool isSpelledInSource(SourceLocation Loc, const SourceManager &SM) {
217 if (Loc.isMacroID()) {
218 std::string PrintLoc = SM.getSpellingLoc(Loc).printToString(SM);
219 if (llvm::StringRef(PrintLoc).startswith("<scratch") ||
220 llvm::StringRef(PrintLoc).startswith("<command line>"))
221 return false;
222 }
223 return true;
224}
225
226SourceLocation spellingLocIfSpelled(SourceLocation Loc,
227 const SourceManager &SM) {
228 if (!isSpelledInSource(Loc, SM))
229 // Use the expansion location as spelling location is not interesting.
230 return SM.getExpansionRange(Loc).getBegin();
231 return SM.getSpellingLoc(Loc);
232}
233
Haojian Wu92c32572019-06-25 08:01:46 +0000234llvm::Optional<Range> getTokenRange(const SourceManager &SM,
235 const LangOptions &LangOpts,
236 SourceLocation TokLoc) {
237 if (!TokLoc.isValid())
238 return llvm::None;
239 SourceLocation End = Lexer::getLocForEndOfToken(TokLoc, 0, SM, LangOpts);
240 if (!End.isValid())
241 return llvm::None;
242 return halfOpenToRange(SM, CharSourceRange::getCharRange(TokLoc, End));
243}
244
Haojian Wu9f2bf662019-10-01 11:03:56 +0000245namespace {
246
247enum TokenFlavor { Identifier, Operator, Whitespace, Other };
248
249bool isOverloadedOperator(const Token &Tok) {
250 switch (Tok.getKind()) {
251#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemOnly) \
252 case tok::Token:
253#define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemOnly)
254#include "clang/Basic/OperatorKinds.def"
255 return true;
256
257 default:
258 break;
259 }
260 return false;
261}
262
263TokenFlavor getTokenFlavor(SourceLocation Loc, const SourceManager &SM,
264 const LangOptions &LangOpts) {
265 Token Tok;
266 Tok.setKind(tok::NUM_TOKENS);
267 if (Lexer::getRawToken(Loc, Tok, SM, LangOpts,
268 /*IgnoreWhiteSpace*/ false))
269 return Other;
270
271 // getRawToken will return false without setting Tok when the token is
272 // whitespace, so if the flag is not set, we are sure this is a whitespace.
273 if (Tok.is(tok::TokenKind::NUM_TOKENS))
274 return Whitespace;
275 if (Tok.is(tok::TokenKind::raw_identifier))
276 return Identifier;
277 if (isOverloadedOperator(Tok))
278 return Operator;
279 return Other;
280}
281
282} // namespace
283
Sam McCall19cefc22019-09-03 15:34:47 +0000284SourceLocation getBeginningOfIdentifier(const Position &Pos,
285 const SourceManager &SM,
286 const LangOptions &LangOpts) {
287 FileID FID = SM.getMainFileID();
288 auto Offset = positionToOffset(SM.getBufferData(FID), Pos);
289 if (!Offset) {
290 log("getBeginningOfIdentifier: {0}", Offset.takeError());
291 return SourceLocation();
292 }
293
Haojian Wu9f2bf662019-10-01 11:03:56 +0000294 // GetBeginningOfToken(InputLoc) is almost what we want, but does the wrong
295 // thing if the cursor is at the end of the token (identifier or operator).
296 // The cases are:
297 // 1) at the beginning of the token
298 // 2) at the middle of the token
299 // 3) at the end of the token
300 // 4) anywhere outside the identifier or operator
301 // To distinguish all cases, we lex both at the
302 // GetBeginningOfToken(InputLoc-1) and GetBeginningOfToken(InputLoc), for
303 // cases 1 and 4, we just return the original location.
Sam McCall19cefc22019-09-03 15:34:47 +0000304 SourceLocation InputLoc = SM.getComposedLoc(FID, *Offset);
Haojian Wu9f2bf662019-10-01 11:03:56 +0000305 if (*Offset == 0) // Case 1 or 4.
Sam McCallb2a984c02019-09-04 10:15:27 +0000306 return InputLoc;
Sam McCall19cefc22019-09-03 15:34:47 +0000307 SourceLocation Before = SM.getComposedLoc(FID, *Offset - 1);
Haojian Wu9f2bf662019-10-01 11:03:56 +0000308 SourceLocation BeforeTokBeginning =
309 Lexer::GetBeginningOfToken(Before, SM, LangOpts);
310 TokenFlavor BeforeKind = getTokenFlavor(BeforeTokBeginning, SM, LangOpts);
Sam McCall19cefc22019-09-03 15:34:47 +0000311
Haojian Wu9f2bf662019-10-01 11:03:56 +0000312 SourceLocation CurrentTokBeginning =
313 Lexer::GetBeginningOfToken(InputLoc, SM, LangOpts);
314 TokenFlavor CurrentKind = getTokenFlavor(CurrentTokBeginning, SM, LangOpts);
315
316 // At the middle of the token.
317 if (BeforeTokBeginning == CurrentTokBeginning) {
318 // For interesting token, we return the beginning of the token.
319 if (CurrentKind == Identifier || CurrentKind == Operator)
320 return CurrentTokBeginning;
321 // otherwise, we return the original loc.
322 return InputLoc;
323 }
324
325 // Whitespace is not interesting.
326 if (BeforeKind == Whitespace)
327 return CurrentTokBeginning;
328 if (CurrentKind == Whitespace)
329 return BeforeTokBeginning;
330
331 // The cursor is at the token boundary, e.g. "Before^Current", we prefer
332 // identifiers to other tokens.
333 if (CurrentKind == Identifier)
334 return CurrentTokBeginning;
335 if (BeforeKind == Identifier)
336 return BeforeTokBeginning;
337 // Then prefer overloaded operators to other tokens.
338 if (CurrentKind == Operator)
339 return CurrentTokBeginning;
340 if (BeforeKind == Operator)
341 return BeforeTokBeginning;
342
343 // Non-interesting case, we just return the original location.
344 return InputLoc;
Sam McCall19cefc22019-09-03 15:34:47 +0000345}
346
Ilya Biryukov43998782019-01-31 21:30:05 +0000347bool isValidFileRange(const SourceManager &Mgr, SourceRange R) {
348 if (!R.getBegin().isValid() || !R.getEnd().isValid())
349 return false;
350
351 FileID BeginFID;
352 size_t BeginOffset = 0;
353 std::tie(BeginFID, BeginOffset) = Mgr.getDecomposedLoc(R.getBegin());
354
355 FileID EndFID;
356 size_t EndOffset = 0;
357 std::tie(EndFID, EndOffset) = Mgr.getDecomposedLoc(R.getEnd());
358
359 return BeginFID.isValid() && BeginFID == EndFID && BeginOffset <= EndOffset;
360}
361
362bool halfOpenRangeContains(const SourceManager &Mgr, SourceRange R,
363 SourceLocation L) {
364 assert(isValidFileRange(Mgr, R));
365
366 FileID BeginFID;
367 size_t BeginOffset = 0;
368 std::tie(BeginFID, BeginOffset) = Mgr.getDecomposedLoc(R.getBegin());
369 size_t EndOffset = Mgr.getFileOffset(R.getEnd());
370
371 FileID LFid;
372 size_t LOffset;
373 std::tie(LFid, LOffset) = Mgr.getDecomposedLoc(L);
374 return BeginFID == LFid && BeginOffset <= LOffset && LOffset < EndOffset;
375}
376
377bool halfOpenRangeTouches(const SourceManager &Mgr, SourceRange R,
378 SourceLocation L) {
379 return L == R.getEnd() || halfOpenRangeContains(Mgr, R, L);
380}
381
Sam McCallc791d852019-08-27 08:44:06 +0000382SourceLocation includeHashLoc(FileID IncludedFile, const SourceManager &SM) {
383 assert(SM.getLocForEndOfFile(IncludedFile).isFileID());
384 FileID IncludingFile;
385 unsigned Offset;
386 std::tie(IncludingFile, Offset) =
387 SM.getDecomposedExpansionLoc(SM.getIncludeLoc(IncludedFile));
388 bool Invalid = false;
389 llvm::StringRef Buf = SM.getBufferData(IncludingFile, &Invalid);
390 if (Invalid)
391 return SourceLocation();
392 // Now buf is "...\n#include <foo>\n..."
393 // and Offset points here: ^
394 // Rewind to the preceding # on the line.
395 assert(Offset < Buf.size());
396 for (;; --Offset) {
397 if (Buf[Offset] == '#')
398 return SM.getComposedLoc(IncludingFile, Offset);
399 if (Buf[Offset] == '\n' || Offset == 0) // no hash, what's going on?
400 return SourceLocation();
401 }
402}
403
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000404static unsigned getTokenLengthAtLoc(SourceLocation Loc, const SourceManager &SM,
405 const LangOptions &LangOpts) {
406 Token TheTok;
407 if (Lexer::getRawToken(Loc, TheTok, SM, LangOpts))
408 return 0;
409 // FIXME: Here we check whether the token at the location is a greatergreater
410 // (>>) token and consider it as a single greater (>). This is to get it
411 // working for templates but it isn't correct for the right shift operator. We
412 // can avoid this by using half open char ranges in getFileRange() but getting
413 // token ending is not well supported in macroIDs.
414 if (TheTok.is(tok::greatergreater))
415 return 1;
416 return TheTok.getLength();
417}
418
419// Returns location of the last character of the token at a given loc
420static SourceLocation getLocForTokenEnd(SourceLocation BeginLoc,
421 const SourceManager &SM,
422 const LangOptions &LangOpts) {
423 unsigned Len = getTokenLengthAtLoc(BeginLoc, SM, LangOpts);
424 return BeginLoc.getLocWithOffset(Len ? Len - 1 : 0);
425}
426
427// Returns location of the starting of the token at a given EndLoc
428static SourceLocation getLocForTokenBegin(SourceLocation EndLoc,
429 const SourceManager &SM,
430 const LangOptions &LangOpts) {
431 return EndLoc.getLocWithOffset(
432 -(signed)getTokenLengthAtLoc(EndLoc, SM, LangOpts));
433}
434
435// Converts a char source range to a token range.
436static SourceRange toTokenRange(CharSourceRange Range, const SourceManager &SM,
437 const LangOptions &LangOpts) {
438 if (!Range.isTokenRange())
439 Range.setEnd(getLocForTokenBegin(Range.getEnd(), SM, LangOpts));
440 return Range.getAsRange();
441}
442// Returns the union of two token ranges.
443// To find the maximum of the Ends of the ranges, we compare the location of the
444// last character of the token.
445static SourceRange unionTokenRange(SourceRange R1, SourceRange R2,
446 const SourceManager &SM,
447 const LangOptions &LangOpts) {
Sam McCallc791d852019-08-27 08:44:06 +0000448 SourceLocation Begin =
449 SM.isBeforeInTranslationUnit(R1.getBegin(), R2.getBegin())
450 ? R1.getBegin()
451 : R2.getBegin();
452 SourceLocation End =
453 SM.isBeforeInTranslationUnit(getLocForTokenEnd(R1.getEnd(), SM, LangOpts),
454 getLocForTokenEnd(R2.getEnd(), SM, LangOpts))
455 ? R2.getEnd()
456 : R1.getEnd();
457 return SourceRange(Begin, End);
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000458}
459
Sam McCallc791d852019-08-27 08:44:06 +0000460// Given a range whose endpoints may be in different expansions or files,
461// tries to find a range within a common file by following up the expansion and
462// include location in each.
463static SourceRange rangeInCommonFile(SourceRange R, const SourceManager &SM,
464 const LangOptions &LangOpts) {
465 // Fast path for most common cases.
466 if (SM.isWrittenInSameFile(R.getBegin(), R.getEnd()))
467 return R;
468 // Record the stack of expansion locations for the beginning, keyed by FileID.
469 llvm::DenseMap<FileID, SourceLocation> BeginExpansions;
470 for (SourceLocation Begin = R.getBegin(); Begin.isValid();
471 Begin = Begin.isFileID()
472 ? includeHashLoc(SM.getFileID(Begin), SM)
473 : SM.getImmediateExpansionRange(Begin).getBegin()) {
474 BeginExpansions[SM.getFileID(Begin)] = Begin;
475 }
476 // Move up the stack of expansion locations for the end until we find the
477 // location in BeginExpansions with that has the same file id.
478 for (SourceLocation End = R.getEnd(); End.isValid();
479 End = End.isFileID() ? includeHashLoc(SM.getFileID(End), SM)
480 : toTokenRange(SM.getImmediateExpansionRange(End),
481 SM, LangOpts)
482 .getEnd()) {
483 auto It = BeginExpansions.find(SM.getFileID(End));
484 if (It != BeginExpansions.end()) {
485 if (SM.getFileOffset(It->second) > SM.getFileOffset(End))
486 return SourceLocation();
487 return {It->second, End};
488 }
489 }
490 return SourceRange();
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000491}
492
493// Find an expansion range (not necessarily immediate) the ends of which are in
494// the same file id.
495static SourceRange
496getExpansionTokenRangeInSameFile(SourceLocation Loc, const SourceManager &SM,
497 const LangOptions &LangOpts) {
Sam McCallc791d852019-08-27 08:44:06 +0000498 return rangeInCommonFile(
499 toTokenRange(SM.getImmediateExpansionRange(Loc), SM, LangOpts), SM,
500 LangOpts);
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000501}
Sam McCallc791d852019-08-27 08:44:06 +0000502
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000503// Returns the file range for a given Location as a Token Range
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000504// This is quite similar to getFileLoc in SourceManager as both use
505// getImmediateExpansionRange and getImmediateSpellingLoc (for macro IDs).
506// However:
507// - We want to maintain the full range information as we move from one file to
508// the next. getFileLoc only uses the BeginLoc of getImmediateExpansionRange.
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000509// - We want to split '>>' tokens as the lexer parses the '>>' in nested
510// template instantiations as a '>>' instead of two '>'s.
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000511// There is also getExpansionRange but it simply calls
512// getImmediateExpansionRange on the begin and ends separately which is wrong.
513static SourceRange getTokenFileRange(SourceLocation Loc,
514 const SourceManager &SM,
515 const LangOptions &LangOpts) {
516 SourceRange FileRange = Loc;
517 while (!FileRange.getBegin().isFileID()) {
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000518 if (SM.isMacroArgExpansion(FileRange.getBegin())) {
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000519 FileRange = unionTokenRange(
520 SM.getImmediateSpellingLoc(FileRange.getBegin()),
521 SM.getImmediateSpellingLoc(FileRange.getEnd()), SM, LangOpts);
Sam McCallc791d852019-08-27 08:44:06 +0000522 assert(SM.isWrittenInSameFile(FileRange.getBegin(), FileRange.getEnd()));
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000523 } else {
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000524 SourceRange ExpansionRangeForBegin =
525 getExpansionTokenRangeInSameFile(FileRange.getBegin(), SM, LangOpts);
526 SourceRange ExpansionRangeForEnd =
527 getExpansionTokenRangeInSameFile(FileRange.getEnd(), SM, LangOpts);
Sam McCallc791d852019-08-27 08:44:06 +0000528 if (ExpansionRangeForBegin.isInvalid() ||
529 ExpansionRangeForEnd.isInvalid())
530 return SourceRange();
531 assert(SM.isWrittenInSameFile(ExpansionRangeForBegin.getBegin(),
532 ExpansionRangeForEnd.getBegin()) &&
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000533 "Both Expansion ranges should be in same file.");
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000534 FileRange = unionTokenRange(ExpansionRangeForBegin, ExpansionRangeForEnd,
535 SM, LangOpts);
536 }
537 }
538 return FileRange;
539}
540
Haojian Wu6ae86ea2019-07-19 08:33:39 +0000541bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM) {
542 return Loc.isValid() && SM.isWrittenInMainFile(SM.getExpansionLoc(Loc));
543}
544
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000545llvm::Optional<SourceRange> toHalfOpenFileRange(const SourceManager &SM,
Ilya Biryukov43998782019-01-31 21:30:05 +0000546 const LangOptions &LangOpts,
547 SourceRange R) {
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000548 SourceRange R1 = getTokenFileRange(R.getBegin(), SM, LangOpts);
549 if (!isValidFileRange(SM, R1))
Ilya Biryukov43998782019-01-31 21:30:05 +0000550 return llvm::None;
Ilya Biryukov43998782019-01-31 21:30:05 +0000551
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000552 SourceRange R2 = getTokenFileRange(R.getEnd(), SM, LangOpts);
553 if (!isValidFileRange(SM, R2))
Ilya Biryukov43998782019-01-31 21:30:05 +0000554 return llvm::None;
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000555
Sam McCallc791d852019-08-27 08:44:06 +0000556 SourceRange Result =
557 rangeInCommonFile(unionTokenRange(R1, R2, SM, LangOpts), SM, LangOpts);
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000558 unsigned TokLen = getTokenLengthAtLoc(Result.getEnd(), SM, LangOpts);
559 // Convert from closed token range to half-open (char) range
560 Result.setEnd(Result.getEnd().getLocWithOffset(TokLen));
561 if (!isValidFileRange(SM, Result))
562 return llvm::None;
563
Ilya Biryukov43998782019-01-31 21:30:05 +0000564 return Result;
565}
566
567llvm::StringRef toSourceCode(const SourceManager &SM, SourceRange R) {
568 assert(isValidFileRange(SM, R));
569 bool Invalid = false;
570 auto *Buf = SM.getBuffer(SM.getFileID(R.getBegin()), &Invalid);
571 assert(!Invalid);
572
573 size_t BeginOffset = SM.getFileOffset(R.getBegin());
574 size_t EndOffset = SM.getFileOffset(R.getEnd());
575 return Buf->getBuffer().substr(BeginOffset, EndOffset - BeginOffset);
576}
577
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000578llvm::Expected<SourceLocation> sourceLocationInMainFile(const SourceManager &SM,
579 Position P) {
580 llvm::StringRef Code = SM.getBuffer(SM.getMainFileID())->getBuffer();
581 auto Offset =
582 positionToOffset(Code, P, /*AllowColumnBeyondLineLength=*/false);
583 if (!Offset)
584 return Offset.takeError();
585 return SM.getLocForStartOfFile(SM.getMainFileID()).getLocWithOffset(*Offset);
586}
587
Ilya Biryukov71028b82018-03-12 15:28:22 +0000588Range halfOpenToRange(const SourceManager &SM, CharSourceRange R) {
589 // Clang is 1-based, LSP uses 0-based indexes.
590 Position Begin = sourceLocToPosition(SM, R.getBegin());
591 Position End = sourceLocToPosition(SM, R.getEnd());
592
593 return {Begin, End};
594}
595
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000596std::pair<size_t, size_t> offsetToClangLineColumn(llvm::StringRef Code,
Sam McCalla4962cc2018-04-27 11:59:28 +0000597 size_t Offset) {
598 Offset = std::min(Code.size(), Offset);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000599 llvm::StringRef Before = Code.substr(0, Offset);
Sam McCalla4962cc2018-04-27 11:59:28 +0000600 int Lines = Before.count('\n');
601 size_t PrevNL = Before.rfind('\n');
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000602 size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
Sam McCalla4962cc2018-04-27 11:59:28 +0000603 return {Lines + 1, Offset - StartOfLine + 1};
604}
605
Ilya Biryukov43998782019-01-31 21:30:05 +0000606std::pair<StringRef, StringRef> splitQualifiedName(StringRef QName) {
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000607 size_t Pos = QName.rfind("::");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000608 if (Pos == llvm::StringRef::npos)
609 return {llvm::StringRef(), QName};
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000610 return {QName.substr(0, Pos + 2), QName.substr(Pos + 2)};
611}
612
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000613TextEdit replacementToEdit(llvm::StringRef Code,
614 const tooling::Replacement &R) {
Eric Liu9133ecd2018-05-11 12:12:08 +0000615 Range ReplacementRange = {
616 offsetToPosition(Code, R.getOffset()),
617 offsetToPosition(Code, R.getOffset() + R.getLength())};
618 return {ReplacementRange, R.getReplacementText()};
619}
620
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000621std::vector<TextEdit> replacementsToEdits(llvm::StringRef Code,
Eric Liu9133ecd2018-05-11 12:12:08 +0000622 const tooling::Replacements &Repls) {
623 std::vector<TextEdit> Edits;
624 for (const auto &R : Repls)
625 Edits.push_back(replacementToEdit(Code, R));
626 return Edits;
627}
628
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000629llvm::Optional<std::string> getCanonicalPath(const FileEntry *F,
630 const SourceManager &SourceMgr) {
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000631 if (!F)
632 return None;
Simon Marchi25f1f732018-08-10 22:27:53 +0000633
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000634 llvm::SmallString<128> FilePath = F->getName();
635 if (!llvm::sys::path::is_absolute(FilePath)) {
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000636 if (auto EC =
Duncan P. N. Exon Smithdb8a7422019-03-26 22:32:06 +0000637 SourceMgr.getFileManager().getVirtualFileSystem().makeAbsolute(
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000638 FilePath)) {
639 elog("Could not turn relative path '{0}' to absolute: {1}", FilePath,
640 EC.message());
Sam McCallc008af62018-10-20 15:30:37 +0000641 return None;
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000642 }
643 }
Simon Marchi25f1f732018-08-10 22:27:53 +0000644
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000645 // Handle the symbolic link path case where the current working directory
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000646 // (getCurrentWorkingDirectory) is a symlink. We always want to the real
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000647 // file path (instead of the symlink path) for the C++ symbols.
648 //
649 // Consider the following example:
650 //
651 // src dir: /project/src/foo.h
652 // current working directory (symlink): /tmp/build -> /project/src/
653 //
654 // The file path of Symbol is "/project/src/foo.h" instead of
655 // "/tmp/build/foo.h"
Harlan Haskinsa02f8572019-08-01 21:32:01 +0000656 if (auto Dir = SourceMgr.getFileManager().getDirectory(
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000657 llvm::sys::path::parent_path(FilePath))) {
658 llvm::SmallString<128> RealPath;
Harlan Haskinsa02f8572019-08-01 21:32:01 +0000659 llvm::StringRef DirName = SourceMgr.getFileManager().getCanonicalName(*Dir);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000660 llvm::sys::path::append(RealPath, DirName,
661 llvm::sys::path::filename(FilePath));
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000662 return RealPath.str().str();
Simon Marchi25f1f732018-08-10 22:27:53 +0000663 }
664
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000665 return FilePath.str().str();
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000666}
667
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +0000668TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M,
669 const LangOptions &L) {
670 TextEdit Result;
671 Result.range =
672 halfOpenToRange(M, Lexer::makeFileCharRange(FixIt.RemoveRange, M, L));
673 Result.newText = FixIt.CodeToInsert;
674 return Result;
675}
676
Haojian Wuaa3ed5a2019-01-25 15:14:03 +0000677bool isRangeConsecutive(const Range &Left, const Range &Right) {
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +0000678 return Left.end.line == Right.start.line &&
679 Left.end.character == Right.start.character;
680}
681
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000682FileDigest digest(llvm::StringRef Content) {
Sam McCall674d8a92019-07-08 11:33:17 +0000683 uint64_t Hash{llvm::xxHash64(Content)};
684 FileDigest Result;
685 for (unsigned I = 0; I < Result.size(); ++I) {
686 Result[I] = uint8_t(Hash);
687 Hash >>= 8;
688 }
689 return Result;
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000690}
691
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000692llvm::Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID) {
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000693 bool Invalid = false;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000694 llvm::StringRef Content = SM.getBufferData(FID, &Invalid);
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000695 if (Invalid)
696 return None;
697 return digest(Content);
698}
699
Eric Liudd662772019-01-28 14:01:55 +0000700format::FormatStyle getFormatStyleForFile(llvm::StringRef File,
701 llvm::StringRef Content,
702 llvm::vfs::FileSystem *FS) {
703 auto Style = format::getStyle(format::DefaultFormatStyle, File,
704 format::DefaultFallbackStyle, Content, FS);
705 if (!Style) {
706 log("getStyle() failed for file {0}: {1}. Fallback is LLVM style.", File,
707 Style.takeError());
708 Style = format::getLLVMStyle();
709 }
710 return *Style;
711}
712
Haojian Wu12e194c2019-02-06 15:24:50 +0000713llvm::Expected<tooling::Replacements>
714cleanupAndFormat(StringRef Code, const tooling::Replacements &Replaces,
715 const format::FormatStyle &Style) {
716 auto CleanReplaces = cleanupAroundReplacements(Code, Replaces, Style);
717 if (!CleanReplaces)
718 return CleanReplaces;
719 return formatReplacements(Code, std::move(*CleanReplaces), Style);
720}
721
Haojian Wuc5e4cf42019-11-07 10:53:19 +0100722static void
723lex(llvm::StringRef Code, const LangOptions &LangOpts,
724 llvm::function_ref<void(const clang::Token &, const SourceManager &SM)>
725 Action) {
Sam McCallc316b222019-04-26 07:45:49 +0000726 // FIXME: InMemoryFileAdapter crashes unless the buffer is null terminated!
727 std::string NullTerminatedCode = Code.str();
728 SourceManagerForFile FileSM("dummy.cpp", NullTerminatedCode);
Eric Liu00d99bd2019-04-11 09:36:36 +0000729 auto &SM = FileSM.get();
730 auto FID = SM.getMainFileID();
Haojian Wu7ea4c6f2019-10-30 13:21:47 +0100731 // Create a raw lexer (with no associated preprocessor object).
732 Lexer Lex(FID, SM.getBuffer(FID), SM, LangOpts);
Eric Liu00d99bd2019-04-11 09:36:36 +0000733 Token Tok;
734
Sam McCallc316b222019-04-26 07:45:49 +0000735 while (!Lex.LexFromRawLexer(Tok))
Haojian Wu7ea4c6f2019-10-30 13:21:47 +0100736 Action(Tok, SM);
Kadir Cetinkaya194117f2019-09-25 14:12:05 +0000737 // LexFromRawLexer returns true after it lexes last token, so we still have
738 // one more token to report.
Haojian Wu7ea4c6f2019-10-30 13:21:47 +0100739 Action(Tok, SM);
Sam McCallc316b222019-04-26 07:45:49 +0000740}
741
742llvm::StringMap<unsigned> collectIdentifiers(llvm::StringRef Content,
743 const format::FormatStyle &Style) {
Eric Liu00d99bd2019-04-11 09:36:36 +0000744 llvm::StringMap<unsigned> Identifiers;
Haojian Wu7ea4c6f2019-10-30 13:21:47 +0100745 auto LangOpt = format::getFormattingLangOpts(Style);
746 lex(Content, LangOpt, [&](const clang::Token &Tok, const SourceManager &) {
747 if (Tok.getKind() == tok::raw_identifier)
Eric Liu00d99bd2019-04-11 09:36:36 +0000748 ++Identifiers[Tok.getRawIdentifier()];
Sam McCallc316b222019-04-26 07:45:49 +0000749 });
Eric Liu00d99bd2019-04-11 09:36:36 +0000750 return Identifiers;
751}
752
Haojian Wu7ea4c6f2019-10-30 13:21:47 +0100753std::vector<Range> collectIdentifierRanges(llvm::StringRef Identifier,
754 llvm::StringRef Content,
755 const LangOptions &LangOpts) {
756 std::vector<Range> Ranges;
757 lex(Content, LangOpts, [&](const clang::Token &Tok, const SourceManager &SM) {
758 if (Tok.getKind() != tok::raw_identifier)
759 return;
760 if (Tok.getRawIdentifier() != Identifier)
761 return;
762 auto Range = getTokenRange(SM, LangOpts, Tok.getLocation());
763 if (!Range)
764 return;
765 Ranges.push_back(*Range);
766 });
767 return Ranges;
768}
769
Sam McCallc316b222019-04-26 07:45:49 +0000770namespace {
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +0200771struct NamespaceEvent {
772 enum {
773 BeginNamespace, // namespace <ns> {. Payload is resolved <ns>.
774 EndNamespace, // } // namespace <ns>. Payload is resolved *outer*
775 // namespace.
776 UsingDirective // using namespace <ns>. Payload is unresolved <ns>.
777 } Trigger;
778 std::string Payload;
779 Position Pos;
Sam McCallc316b222019-04-26 07:45:49 +0000780};
781// Scans C++ source code for constructs that change the visible namespaces.
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +0200782void parseNamespaceEvents(llvm::StringRef Code,
783 const format::FormatStyle &Style,
784 llvm::function_ref<void(NamespaceEvent)> Callback) {
Sam McCallc316b222019-04-26 07:45:49 +0000785
786 // Stack of enclosing namespaces, e.g. {"clang", "clangd"}
787 std::vector<std::string> Enclosing; // Contains e.g. "clang", "clangd"
788 // Stack counts open braces. true if the brace opened a namespace.
789 std::vector<bool> BraceStack;
790
791 enum {
792 Default,
793 Namespace, // just saw 'namespace'
794 NamespaceName, // just saw 'namespace' NSName
795 Using, // just saw 'using'
796 UsingNamespace, // just saw 'using namespace'
797 UsingNamespaceName, // just saw 'using namespace' NSName
798 } State = Default;
799 std::string NSName;
800
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +0200801 NamespaceEvent Event;
Haojian Wu7ea4c6f2019-10-30 13:21:47 +0100802 lex(Code, format::getFormattingLangOpts(Style),
803 [&](const clang::Token &Tok,const SourceManager &SM) {
804 Event.Pos = sourceLocToPosition(SM, Tok.getLocation());
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +0200805 switch (Tok.getKind()) {
Sam McCallc316b222019-04-26 07:45:49 +0000806 case tok::raw_identifier:
807 // In raw mode, this could be a keyword or a name.
808 switch (State) {
809 case UsingNamespace:
810 case UsingNamespaceName:
811 NSName.append(Tok.getRawIdentifier());
812 State = UsingNamespaceName;
813 break;
814 case Namespace:
815 case NamespaceName:
816 NSName.append(Tok.getRawIdentifier());
817 State = NamespaceName;
818 break;
819 case Using:
820 State =
821 (Tok.getRawIdentifier() == "namespace") ? UsingNamespace : Default;
822 break;
823 case Default:
824 NSName.clear();
825 if (Tok.getRawIdentifier() == "namespace")
826 State = Namespace;
827 else if (Tok.getRawIdentifier() == "using")
828 State = Using;
829 break;
830 }
831 break;
832 case tok::coloncolon:
833 // This can come at the beginning or in the middle of a namespace name.
834 switch (State) {
835 case UsingNamespace:
836 case UsingNamespaceName:
837 NSName.append("::");
838 State = UsingNamespaceName;
839 break;
840 case NamespaceName:
841 NSName.append("::");
842 State = NamespaceName;
843 break;
844 case Namespace: // Not legal here.
845 case Using:
846 case Default:
847 State = Default;
848 break;
849 }
850 break;
851 case tok::l_brace:
852 // Record which { started a namespace, so we know when } ends one.
853 if (State == NamespaceName) {
854 // Parsed: namespace <name> {
855 BraceStack.push_back(true);
856 Enclosing.push_back(NSName);
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +0200857 Event.Trigger = NamespaceEvent::BeginNamespace;
858 Event.Payload = llvm::join(Enclosing, "::");
859 Callback(Event);
Sam McCallc316b222019-04-26 07:45:49 +0000860 } else {
861 // This case includes anonymous namespaces (State = Namespace).
862 // For our purposes, they're not namespaces and we ignore them.
863 BraceStack.push_back(false);
864 }
865 State = Default;
866 break;
867 case tok::r_brace:
868 // If braces are unmatched, we're going to be confused, but don't crash.
869 if (!BraceStack.empty()) {
870 if (BraceStack.back()) {
871 // Parsed: } // namespace
872 Enclosing.pop_back();
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +0200873 Event.Trigger = NamespaceEvent::EndNamespace;
874 Event.Payload = llvm::join(Enclosing, "::");
875 Callback(Event);
Sam McCallc316b222019-04-26 07:45:49 +0000876 }
877 BraceStack.pop_back();
878 }
879 break;
880 case tok::semi:
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +0200881 if (State == UsingNamespaceName) {
Sam McCallc316b222019-04-26 07:45:49 +0000882 // Parsed: using namespace <name> ;
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +0200883 Event.Trigger = NamespaceEvent::UsingDirective;
884 Event.Payload = std::move(NSName);
885 Callback(Event);
886 }
Sam McCallc316b222019-04-26 07:45:49 +0000887 State = Default;
888 break;
889 default:
890 State = Default;
891 break;
892 }
893 });
894}
895
896// Returns the prefix namespaces of NS: {"" ... NS}.
897llvm::SmallVector<llvm::StringRef, 8> ancestorNamespaces(llvm::StringRef NS) {
898 llvm::SmallVector<llvm::StringRef, 8> Results;
899 Results.push_back(NS.take_front(0));
900 NS.split(Results, "::", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
901 for (llvm::StringRef &R : Results)
902 R = NS.take_front(R.end() - NS.begin());
903 return Results;
904}
905
906} // namespace
907
908std::vector<std::string> visibleNamespaces(llvm::StringRef Code,
909 const format::FormatStyle &Style) {
910 std::string Current;
911 // Map from namespace to (resolved) namespaces introduced via using directive.
912 llvm::StringMap<llvm::StringSet<>> UsingDirectives;
913
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +0200914 parseNamespaceEvents(Code, Style, [&](NamespaceEvent Event) {
915 llvm::StringRef NS = Event.Payload;
916 switch (Event.Trigger) {
917 case NamespaceEvent::BeginNamespace:
918 case NamespaceEvent::EndNamespace:
919 Current = std::move(Event.Payload);
920 break;
921 case NamespaceEvent::UsingDirective:
922 if (NS.consume_front("::"))
923 UsingDirectives[Current].insert(NS);
924 else {
925 for (llvm::StringRef Enclosing : ancestorNamespaces(Current)) {
926 if (Enclosing.empty())
927 UsingDirectives[Current].insert(NS);
928 else
929 UsingDirectives[Current].insert((Enclosing + "::" + NS).str());
930 }
931 }
932 break;
933 }
934 });
Sam McCallc316b222019-04-26 07:45:49 +0000935
936 std::vector<std::string> Found;
937 for (llvm::StringRef Enclosing : ancestorNamespaces(Current)) {
938 Found.push_back(Enclosing);
939 auto It = UsingDirectives.find(Enclosing);
940 if (It != UsingDirectives.end())
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +0200941 for (const auto &Used : It->second)
Sam McCallc316b222019-04-26 07:45:49 +0000942 Found.push_back(Used.getKey());
943 }
944
Sam McCallc316b222019-04-26 07:45:49 +0000945 llvm::sort(Found, [&](const std::string &LHS, const std::string &RHS) {
946 if (Current == RHS)
947 return false;
948 if (Current == LHS)
949 return true;
950 return LHS < RHS;
951 });
952 Found.erase(std::unique(Found.begin(), Found.end()), Found.end());
953 return Found;
954}
955
Sam McCall9fb22b22019-05-06 10:25:10 +0000956llvm::StringSet<> collectWords(llvm::StringRef Content) {
957 // We assume short words are not significant.
958 // We may want to consider other stopwords, e.g. language keywords.
959 // (A very naive implementation showed no benefit, but lexing might do better)
960 static constexpr int MinWordLength = 4;
961
962 std::vector<CharRole> Roles(Content.size());
963 calculateRoles(Content, Roles);
964
965 llvm::StringSet<> Result;
966 llvm::SmallString<256> Word;
967 auto Flush = [&] {
968 if (Word.size() >= MinWordLength) {
969 for (char &C : Word)
970 C = llvm::toLower(C);
971 Result.insert(Word);
972 }
973 Word.clear();
974 };
975 for (unsigned I = 0; I < Content.size(); ++I) {
976 switch (Roles[I]) {
977 case Head:
978 Flush();
979 LLVM_FALLTHROUGH;
980 case Tail:
981 Word.push_back(Content[I]);
982 break;
983 case Unknown:
984 case Separator:
985 Flush();
986 break;
987 }
988 }
989 Flush();
990
991 return Result;
992}
993
Haojian Wu9d34f452019-07-01 09:26:48 +0000994llvm::Optional<DefinedMacro> locateMacroAt(SourceLocation Loc,
995 Preprocessor &PP) {
996 const auto &SM = PP.getSourceManager();
997 const auto &LangOpts = PP.getLangOpts();
998 Token Result;
999 if (Lexer::getRawToken(SM.getSpellingLoc(Loc), Result, SM, LangOpts, false))
1000 return None;
1001 if (Result.is(tok::raw_identifier))
1002 PP.LookUpIdentifierInfo(Result);
1003 IdentifierInfo *IdentifierInfo = Result.getIdentifierInfo();
1004 if (!IdentifierInfo || !IdentifierInfo->hadMacroDefinition())
1005 return None;
1006
1007 std::pair<FileID, unsigned int> DecLoc = SM.getDecomposedExpansionLoc(Loc);
1008 // Get the definition just before the searched location so that a macro
1009 // referenced in a '#undef MACRO' can still be found.
1010 SourceLocation BeforeSearchedLocation =
1011 SM.getMacroArgExpandedLocation(SM.getLocForStartOfFile(DecLoc.first)
1012 .getLocWithOffset(DecLoc.second - 1));
1013 MacroDefinition MacroDef =
1014 PP.getMacroDefinitionAtLoc(IdentifierInfo, BeforeSearchedLocation);
1015 if (auto *MI = MacroDef.getMacroInfo())
1016 return DefinedMacro{IdentifierInfo->getName(), MI};
1017 return None;
1018}
1019
Kadir Cetinkaya5b270932019-09-09 12:28:44 +00001020llvm::Expected<std::string> Edit::apply() const {
1021 return tooling::applyAllReplacements(InitialCode, Replacements);
1022}
1023
1024std::vector<TextEdit> Edit::asTextEdits() const {
1025 return replacementsToEdits(InitialCode, Replacements);
1026}
1027
1028bool Edit::canApplyTo(llvm::StringRef Code) const {
1029 // Create line iterators, since line numbers are important while applying our
1030 // edit we cannot skip blank lines.
1031 auto LHS = llvm::MemoryBuffer::getMemBuffer(Code);
1032 llvm::line_iterator LHSIt(*LHS, /*SkipBlanks=*/false);
1033
1034 auto RHS = llvm::MemoryBuffer::getMemBuffer(InitialCode);
1035 llvm::line_iterator RHSIt(*RHS, /*SkipBlanks=*/false);
1036
1037 // Compare the InitialCode we prepared the edit for with the Code we received
1038 // line by line to make sure there are no differences.
1039 // FIXME: This check is too conservative now, it should be enough to only
1040 // check lines around the replacements contained inside the Edit.
1041 while (!LHSIt.is_at_eof() && !RHSIt.is_at_eof()) {
1042 if (*LHSIt != *RHSIt)
1043 return false;
1044 ++LHSIt;
1045 ++RHSIt;
1046 }
1047
1048 // After we reach EOF for any of the files we make sure the other one doesn't
1049 // contain any additional content except empty lines, they should not
1050 // interfere with the edit we produced.
1051 while (!LHSIt.is_at_eof()) {
1052 if (!LHSIt->empty())
1053 return false;
1054 ++LHSIt;
1055 }
1056 while (!RHSIt.is_at_eof()) {
1057 if (!RHSIt->empty())
1058 return false;
1059 ++RHSIt;
1060 }
1061 return true;
1062}
1063
1064llvm::Error reformatEdit(Edit &E, const format::FormatStyle &Style) {
1065 if (auto NewEdits = cleanupAndFormat(E.InitialCode, E.Replacements, Style))
1066 E.Replacements = std::move(*NewEdits);
1067 else
1068 return NewEdits.takeError();
1069 return llvm::Error::success();
1070}
1071
Kadir Cetinkayad62e3ed2019-09-25 11:35:38 +02001072EligibleRegion getEligiblePoints(llvm::StringRef Code,
1073 llvm::StringRef FullyQualifiedName,
1074 const format::FormatStyle &Style) {
1075 EligibleRegion ER;
1076 // Start with global namespace.
1077 std::vector<std::string> Enclosing = {""};
1078 // FIXME: In addition to namespaces try to generate events for function
1079 // definitions as well. One might use a closing parantheses(")" followed by an
1080 // opening brace "{" to trigger the start.
1081 parseNamespaceEvents(Code, Style, [&](NamespaceEvent Event) {
1082 // Using Directives only introduces declarations to current scope, they do
1083 // not change the current namespace, so skip them.
1084 if (Event.Trigger == NamespaceEvent::UsingDirective)
1085 return;
1086 // Do not qualify the global namespace.
1087 if (!Event.Payload.empty())
1088 Event.Payload.append("::");
1089
1090 std::string CurrentNamespace;
1091 if (Event.Trigger == NamespaceEvent::BeginNamespace) {
1092 Enclosing.emplace_back(std::move(Event.Payload));
1093 CurrentNamespace = Enclosing.back();
1094 // parseNameSpaceEvents reports the beginning position of a token; we want
1095 // to insert after '{', so increment by one.
1096 ++Event.Pos.character;
1097 } else {
1098 // Event.Payload points to outer namespace when exiting a scope, so use
1099 // the namespace we've last entered instead.
1100 CurrentNamespace = std::move(Enclosing.back());
1101 Enclosing.pop_back();
1102 assert(Enclosing.back() == Event.Payload);
1103 }
1104
1105 // Ignore namespaces that are not a prefix of the target.
1106 if (!FullyQualifiedName.startswith(CurrentNamespace))
1107 return;
1108
1109 // Prefer the namespace that shares the longest prefix with target.
1110 if (CurrentNamespace.size() > ER.EnclosingNamespace.size()) {
1111 ER.EligiblePoints.clear();
1112 ER.EnclosingNamespace = CurrentNamespace;
1113 }
1114 if (CurrentNamespace.size() == ER.EnclosingNamespace.size())
1115 ER.EligiblePoints.emplace_back(std::move(Event.Pos));
1116 });
1117 // If there were no shared namespaces just return EOF.
1118 if (ER.EligiblePoints.empty()) {
1119 assert(ER.EnclosingNamespace.empty());
1120 ER.EligiblePoints.emplace_back(offsetToPosition(Code, Code.size()));
1121 }
1122 return ER;
1123}
1124
Sam McCallb536a2a2017-12-19 12:23:48 +00001125} // namespace clangd
1126} // namespace clang