blob: 42910163bd9bee78286e7fec77ec0110551a3812 [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"
Marc-Andre Laperle1be69702018-07-05 19:35:01 +000014#include "clang/AST/ASTContext.h"
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +000015#include "clang/Basic/LangOptions.h"
16#include "clang/Basic/SourceLocation.h"
Marc-Andre Laperle63a10982018-02-21 02:39:08 +000017#include "clang/Basic/SourceManager.h"
Sam McCallc316b222019-04-26 07:45:49 +000018#include "clang/Basic/TokenKinds.h"
19#include "clang/Format/Format.h"
Marc-Andre Laperle1be69702018-07-05 19:35:01 +000020#include "clang/Lex/Lexer.h"
Haojian Wu9d34f452019-07-01 09:26:48 +000021#include "clang/Lex/Preprocessor.h"
Ilya Biryukov43998782019-01-31 21:30:05 +000022#include "llvm/ADT/None.h"
Sam McCallc316b222019-04-26 07:45:49 +000023#include "llvm/ADT/StringExtras.h"
Ilya Biryukov43998782019-01-31 21:30:05 +000024#include "llvm/ADT/StringRef.h"
Sam McCall9fb22b22019-05-06 10:25:10 +000025#include "llvm/Support/Compiler.h"
Simon Marchi766338a2018-03-21 14:36:46 +000026#include "llvm/Support/Errc.h"
27#include "llvm/Support/Error.h"
Sam McCall8b25d222019-03-28 14:37:51 +000028#include "llvm/Support/ErrorHandling.h"
Marc-Andre Laperle1be69702018-07-05 19:35:01 +000029#include "llvm/Support/Path.h"
Sam McCall674d8a92019-07-08 11:33:17 +000030#include "llvm/Support/xxhash.h"
Sam McCallc316b222019-04-26 07:45:49 +000031#include <algorithm>
Marc-Andre Laperle63a10982018-02-21 02:39:08 +000032
Sam McCallb536a2a2017-12-19 12:23:48 +000033namespace clang {
34namespace clangd {
Sam McCallb536a2a2017-12-19 12:23:48 +000035
Sam McCalla4962cc2018-04-27 11:59:28 +000036// Here be dragons. LSP positions use columns measured in *UTF-16 code units*!
37// Clangd uses UTF-8 and byte-offsets internally, so conversion is nontrivial.
38
39// Iterates over unicode codepoints in the (UTF-8) string. For each,
40// invokes CB(UTF-8 length, UTF-16 length), and breaks if it returns true.
41// Returns true if CB returned true, false if we hit the end of string.
42template <typename Callback>
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000043static bool iterateCodepoints(llvm::StringRef U8, const Callback &CB) {
Sam McCall8b25d222019-03-28 14:37:51 +000044 // A codepoint takes two UTF-16 code unit if it's astral (outside BMP).
45 // Astral codepoints are encoded as 4 bytes in UTF-8, starting with 11110xxx.
Sam McCalla4962cc2018-04-27 11:59:28 +000046 for (size_t I = 0; I < U8.size();) {
47 unsigned char C = static_cast<unsigned char>(U8[I]);
48 if (LLVM_LIKELY(!(C & 0x80))) { // ASCII character.
49 if (CB(1, 1))
50 return true;
51 ++I;
52 continue;
53 }
54 // This convenient property of UTF-8 holds for all non-ASCII characters.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000055 size_t UTF8Length = llvm::countLeadingOnes(C);
Sam McCalla4962cc2018-04-27 11:59:28 +000056 // 0xxx is ASCII, handled above. 10xxx is a trailing byte, invalid here.
57 // 11111xxx is not valid UTF-8 at all. Assert because it's probably our bug.
58 assert((UTF8Length >= 2 && UTF8Length <= 4) &&
59 "Invalid UTF-8, or transcoding bug?");
60 I += UTF8Length; // Skip over all trailing bytes.
61 // A codepoint takes two UTF-16 code unit if it's astral (outside BMP).
62 // Astral codepoints are encoded as 4 bytes in UTF-8 (11110xxx ...)
63 if (CB(UTF8Length, UTF8Length == 4 ? 2 : 1))
64 return true;
65 }
66 return false;
67}
68
Sam McCall8b25d222019-03-28 14:37:51 +000069// Returns the byte offset into the string that is an offset of \p Units in
70// the specified encoding.
71// Conceptually, this converts to the encoding, truncates to CodeUnits,
72// converts back to UTF-8, and returns the length in bytes.
73static size_t measureUnits(llvm::StringRef U8, int Units, OffsetEncoding Enc,
74 bool &Valid) {
75 Valid = Units >= 0;
76 if (Units <= 0)
77 return 0;
Sam McCalla4962cc2018-04-27 11:59:28 +000078 size_t Result = 0;
Sam McCall8b25d222019-03-28 14:37:51 +000079 switch (Enc) {
80 case OffsetEncoding::UTF8:
81 Result = Units;
82 break;
83 case OffsetEncoding::UTF16:
84 Valid = iterateCodepoints(U8, [&](int U8Len, int U16Len) {
85 Result += U8Len;
86 Units -= U16Len;
87 return Units <= 0;
88 });
89 if (Units < 0) // Offset in the middle of a surrogate pair.
90 Valid = false;
91 break;
92 case OffsetEncoding::UTF32:
93 Valid = iterateCodepoints(U8, [&](int U8Len, int U16Len) {
94 Result += U8Len;
95 Units--;
96 return Units <= 0;
97 });
98 break;
99 case OffsetEncoding::UnsupportedEncoding:
100 llvm_unreachable("unsupported encoding");
101 }
Sam McCalla4962cc2018-04-27 11:59:28 +0000102 // Don't return an out-of-range index if we overran.
Sam McCall8b25d222019-03-28 14:37:51 +0000103 if (Result > U8.size()) {
104 Valid = false;
105 return U8.size();
106 }
107 return Result;
Sam McCalla4962cc2018-04-27 11:59:28 +0000108}
109
Sam McCalla69698f2019-03-27 17:47:49 +0000110Key<OffsetEncoding> kCurrentOffsetEncoding;
Sam McCall8b25d222019-03-28 14:37:51 +0000111static OffsetEncoding lspEncoding() {
Sam McCalla69698f2019-03-27 17:47:49 +0000112 auto *Enc = Context::current().get(kCurrentOffsetEncoding);
Sam McCall8b25d222019-03-28 14:37:51 +0000113 return Enc ? *Enc : OffsetEncoding::UTF16;
Sam McCalla69698f2019-03-27 17:47:49 +0000114}
115
Sam McCalla4962cc2018-04-27 11:59:28 +0000116// Like most strings in clangd, the input is UTF-8 encoded.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000117size_t lspLength(llvm::StringRef Code) {
Sam McCalla4962cc2018-04-27 11:59:28 +0000118 size_t Count = 0;
Sam McCall8b25d222019-03-28 14:37:51 +0000119 switch (lspEncoding()) {
120 case OffsetEncoding::UTF8:
121 Count = Code.size();
122 break;
123 case OffsetEncoding::UTF16:
124 iterateCodepoints(Code, [&](int U8Len, int U16Len) {
125 Count += U16Len;
126 return false;
127 });
128 break;
129 case OffsetEncoding::UTF32:
130 iterateCodepoints(Code, [&](int U8Len, int U16Len) {
131 ++Count;
132 return false;
133 });
134 break;
135 case OffsetEncoding::UnsupportedEncoding:
136 llvm_unreachable("unsupported encoding");
137 }
Sam McCalla4962cc2018-04-27 11:59:28 +0000138 return Count;
139}
140
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000141llvm::Expected<size_t> positionToOffset(llvm::StringRef Code, Position P,
142 bool AllowColumnsBeyondLineLength) {
Sam McCallb536a2a2017-12-19 12:23:48 +0000143 if (P.line < 0)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000144 return llvm::make_error<llvm::StringError>(
145 llvm::formatv("Line value can't be negative ({0})", P.line),
146 llvm::errc::invalid_argument);
Simon Marchi766338a2018-03-21 14:36:46 +0000147 if (P.character < 0)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000148 return llvm::make_error<llvm::StringError>(
149 llvm::formatv("Character value can't be negative ({0})", P.character),
150 llvm::errc::invalid_argument);
Sam McCallb536a2a2017-12-19 12:23:48 +0000151 size_t StartOfLine = 0;
152 for (int I = 0; I != P.line; ++I) {
153 size_t NextNL = Code.find('\n', StartOfLine);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000154 if (NextNL == llvm::StringRef::npos)
155 return llvm::make_error<llvm::StringError>(
156 llvm::formatv("Line value is out of range ({0})", P.line),
157 llvm::errc::invalid_argument);
Sam McCallb536a2a2017-12-19 12:23:48 +0000158 StartOfLine = NextNL + 1;
159 }
Sam McCalla69698f2019-03-27 17:47:49 +0000160 StringRef Line =
161 Code.substr(StartOfLine).take_until([](char C) { return C == '\n'; });
Simon Marchi766338a2018-03-21 14:36:46 +0000162
Sam McCall8b25d222019-03-28 14:37:51 +0000163 // P.character may be in UTF-16, transcode if necessary.
Sam McCalla4962cc2018-04-27 11:59:28 +0000164 bool Valid;
Sam McCall8b25d222019-03-28 14:37:51 +0000165 size_t ByteInLine = measureUnits(Line, P.character, lspEncoding(), Valid);
Sam McCalla4962cc2018-04-27 11:59:28 +0000166 if (!Valid && !AllowColumnsBeyondLineLength)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000167 return llvm::make_error<llvm::StringError>(
Sam McCall8b25d222019-03-28 14:37:51 +0000168 llvm::formatv("{0} offset {1} is invalid for line {2}", lspEncoding(),
169 P.character, P.line),
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000170 llvm::errc::invalid_argument);
Sam McCall8b25d222019-03-28 14:37:51 +0000171 return StartOfLine + ByteInLine;
Sam McCallb536a2a2017-12-19 12:23:48 +0000172}
173
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000174Position offsetToPosition(llvm::StringRef Code, size_t Offset) {
Sam McCallb536a2a2017-12-19 12:23:48 +0000175 Offset = std::min(Code.size(), Offset);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000176 llvm::StringRef Before = Code.substr(0, Offset);
Sam McCallb536a2a2017-12-19 12:23:48 +0000177 int Lines = Before.count('\n');
178 size_t PrevNL = Before.rfind('\n');
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000179 size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
Ilya Biryukov7beea3a2018-02-14 10:52:04 +0000180 Position Pos;
181 Pos.line = Lines;
Sam McCall71891122018-10-23 11:51:53 +0000182 Pos.character = lspLength(Before.substr(StartOfLine));
Ilya Biryukov7beea3a2018-02-14 10:52:04 +0000183 return Pos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000184}
185
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000186Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc) {
Sam McCalla4962cc2018-04-27 11:59:28 +0000187 // We use the SourceManager's line tables, but its column number is in bytes.
188 FileID FID;
189 unsigned Offset;
190 std::tie(FID, Offset) = SM.getDecomposedSpellingLoc(Loc);
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000191 Position P;
Sam McCalla4962cc2018-04-27 11:59:28 +0000192 P.line = static_cast<int>(SM.getLineNumber(FID, Offset)) - 1;
193 bool Invalid = false;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000194 llvm::StringRef Code = SM.getBufferData(FID, &Invalid);
Sam McCalla4962cc2018-04-27 11:59:28 +0000195 if (!Invalid) {
196 auto ColumnInBytes = SM.getColumnNumber(FID, Offset) - 1;
197 auto LineSoFar = Code.substr(Offset - ColumnInBytes, ColumnInBytes);
Sam McCall71891122018-10-23 11:51:53 +0000198 P.character = lspLength(LineSoFar);
Sam McCalla4962cc2018-04-27 11:59:28 +0000199 }
Marc-Andre Laperle63a10982018-02-21 02:39:08 +0000200 return P;
201}
202
Sam McCall95738072019-08-06 20:25:59 +0000203bool isSpelledInSource(SourceLocation Loc, const SourceManager &SM) {
204 if (Loc.isMacroID()) {
205 std::string PrintLoc = SM.getSpellingLoc(Loc).printToString(SM);
206 if (llvm::StringRef(PrintLoc).startswith("<scratch") ||
207 llvm::StringRef(PrintLoc).startswith("<command line>"))
208 return false;
209 }
210 return true;
211}
212
213SourceLocation spellingLocIfSpelled(SourceLocation Loc,
214 const SourceManager &SM) {
215 if (!isSpelledInSource(Loc, SM))
216 // Use the expansion location as spelling location is not interesting.
217 return SM.getExpansionRange(Loc).getBegin();
218 return SM.getSpellingLoc(Loc);
219}
220
Haojian Wu92c32572019-06-25 08:01:46 +0000221llvm::Optional<Range> getTokenRange(const SourceManager &SM,
222 const LangOptions &LangOpts,
223 SourceLocation TokLoc) {
224 if (!TokLoc.isValid())
225 return llvm::None;
226 SourceLocation End = Lexer::getLocForEndOfToken(TokLoc, 0, SM, LangOpts);
227 if (!End.isValid())
228 return llvm::None;
229 return halfOpenToRange(SM, CharSourceRange::getCharRange(TokLoc, End));
230}
231
Sam McCall19cefc22019-09-03 15:34:47 +0000232SourceLocation getBeginningOfIdentifier(const Position &Pos,
233 const SourceManager &SM,
234 const LangOptions &LangOpts) {
235 FileID FID = SM.getMainFileID();
236 auto Offset = positionToOffset(SM.getBufferData(FID), Pos);
237 if (!Offset) {
238 log("getBeginningOfIdentifier: {0}", Offset.takeError());
239 return SourceLocation();
240 }
241
242 // GetBeginningOfToken(pos) is almost what we want, but does the wrong thing
243 // if the cursor is at the end of the identifier.
244 // Instead, we lex at GetBeginningOfToken(pos - 1). The cases are:
245 // 1) at the beginning of an identifier, we'll be looking at something
246 // that isn't an identifier.
247 // 2) at the middle or end of an identifier, we get the identifier.
248 // 3) anywhere outside an identifier, we'll get some non-identifier thing.
249 // We can't actually distinguish cases 1 and 3, but returning the original
250 // location is correct for both!
251 SourceLocation InputLoc = SM.getComposedLoc(FID, *Offset);
252 if (*Offset == 0) // Case 1 or 3.
253 return SM.getMacroArgExpandedLocation(InputLoc);
254 SourceLocation Before = SM.getComposedLoc(FID, *Offset - 1);
255
256 Before = Lexer::GetBeginningOfToken(Before, SM, LangOpts);
257 Token Tok;
258 if (Before.isValid() &&
259 !Lexer::getRawToken(Before, Tok, SM, LangOpts, false) &&
260 Tok.is(tok::raw_identifier))
261 return SM.getMacroArgExpandedLocation(Before); // Case 2.
262 return SM.getMacroArgExpandedLocation(InputLoc); // Case 1 or 3.
263}
264
Ilya Biryukov43998782019-01-31 21:30:05 +0000265bool isValidFileRange(const SourceManager &Mgr, SourceRange R) {
266 if (!R.getBegin().isValid() || !R.getEnd().isValid())
267 return false;
268
269 FileID BeginFID;
270 size_t BeginOffset = 0;
271 std::tie(BeginFID, BeginOffset) = Mgr.getDecomposedLoc(R.getBegin());
272
273 FileID EndFID;
274 size_t EndOffset = 0;
275 std::tie(EndFID, EndOffset) = Mgr.getDecomposedLoc(R.getEnd());
276
277 return BeginFID.isValid() && BeginFID == EndFID && BeginOffset <= EndOffset;
278}
279
280bool halfOpenRangeContains(const SourceManager &Mgr, SourceRange R,
281 SourceLocation L) {
282 assert(isValidFileRange(Mgr, R));
283
284 FileID BeginFID;
285 size_t BeginOffset = 0;
286 std::tie(BeginFID, BeginOffset) = Mgr.getDecomposedLoc(R.getBegin());
287 size_t EndOffset = Mgr.getFileOffset(R.getEnd());
288
289 FileID LFid;
290 size_t LOffset;
291 std::tie(LFid, LOffset) = Mgr.getDecomposedLoc(L);
292 return BeginFID == LFid && BeginOffset <= LOffset && LOffset < EndOffset;
293}
294
295bool halfOpenRangeTouches(const SourceManager &Mgr, SourceRange R,
296 SourceLocation L) {
297 return L == R.getEnd() || halfOpenRangeContains(Mgr, R, L);
298}
299
Sam McCallc791d852019-08-27 08:44:06 +0000300SourceLocation includeHashLoc(FileID IncludedFile, const SourceManager &SM) {
301 assert(SM.getLocForEndOfFile(IncludedFile).isFileID());
302 FileID IncludingFile;
303 unsigned Offset;
304 std::tie(IncludingFile, Offset) =
305 SM.getDecomposedExpansionLoc(SM.getIncludeLoc(IncludedFile));
306 bool Invalid = false;
307 llvm::StringRef Buf = SM.getBufferData(IncludingFile, &Invalid);
308 if (Invalid)
309 return SourceLocation();
310 // Now buf is "...\n#include <foo>\n..."
311 // and Offset points here: ^
312 // Rewind to the preceding # on the line.
313 assert(Offset < Buf.size());
314 for (;; --Offset) {
315 if (Buf[Offset] == '#')
316 return SM.getComposedLoc(IncludingFile, Offset);
317 if (Buf[Offset] == '\n' || Offset == 0) // no hash, what's going on?
318 return SourceLocation();
319 }
320}
321
322
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000323static unsigned getTokenLengthAtLoc(SourceLocation Loc, const SourceManager &SM,
324 const LangOptions &LangOpts) {
325 Token TheTok;
326 if (Lexer::getRawToken(Loc, TheTok, SM, LangOpts))
327 return 0;
328 // FIXME: Here we check whether the token at the location is a greatergreater
329 // (>>) token and consider it as a single greater (>). This is to get it
330 // working for templates but it isn't correct for the right shift operator. We
331 // can avoid this by using half open char ranges in getFileRange() but getting
332 // token ending is not well supported in macroIDs.
333 if (TheTok.is(tok::greatergreater))
334 return 1;
335 return TheTok.getLength();
336}
337
338// Returns location of the last character of the token at a given loc
339static SourceLocation getLocForTokenEnd(SourceLocation BeginLoc,
340 const SourceManager &SM,
341 const LangOptions &LangOpts) {
342 unsigned Len = getTokenLengthAtLoc(BeginLoc, SM, LangOpts);
343 return BeginLoc.getLocWithOffset(Len ? Len - 1 : 0);
344}
345
346// Returns location of the starting of the token at a given EndLoc
347static SourceLocation getLocForTokenBegin(SourceLocation EndLoc,
348 const SourceManager &SM,
349 const LangOptions &LangOpts) {
350 return EndLoc.getLocWithOffset(
351 -(signed)getTokenLengthAtLoc(EndLoc, SM, LangOpts));
352}
353
354// Converts a char source range to a token range.
355static SourceRange toTokenRange(CharSourceRange Range, const SourceManager &SM,
356 const LangOptions &LangOpts) {
357 if (!Range.isTokenRange())
358 Range.setEnd(getLocForTokenBegin(Range.getEnd(), SM, LangOpts));
359 return Range.getAsRange();
360}
361// Returns the union of two token ranges.
362// To find the maximum of the Ends of the ranges, we compare the location of the
363// last character of the token.
364static SourceRange unionTokenRange(SourceRange R1, SourceRange R2,
365 const SourceManager &SM,
366 const LangOptions &LangOpts) {
Sam McCallc791d852019-08-27 08:44:06 +0000367 SourceLocation Begin =
368 SM.isBeforeInTranslationUnit(R1.getBegin(), R2.getBegin())
369 ? R1.getBegin()
370 : R2.getBegin();
371 SourceLocation End =
372 SM.isBeforeInTranslationUnit(getLocForTokenEnd(R1.getEnd(), SM, LangOpts),
373 getLocForTokenEnd(R2.getEnd(), SM, LangOpts))
374 ? R2.getEnd()
375 : R1.getEnd();
376 return SourceRange(Begin, End);
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000377}
378
Sam McCallc791d852019-08-27 08:44:06 +0000379// Given a range whose endpoints may be in different expansions or files,
380// tries to find a range within a common file by following up the expansion and
381// include location in each.
382static SourceRange rangeInCommonFile(SourceRange R, const SourceManager &SM,
383 const LangOptions &LangOpts) {
384 // Fast path for most common cases.
385 if (SM.isWrittenInSameFile(R.getBegin(), R.getEnd()))
386 return R;
387 // Record the stack of expansion locations for the beginning, keyed by FileID.
388 llvm::DenseMap<FileID, SourceLocation> BeginExpansions;
389 for (SourceLocation Begin = R.getBegin(); Begin.isValid();
390 Begin = Begin.isFileID()
391 ? includeHashLoc(SM.getFileID(Begin), SM)
392 : SM.getImmediateExpansionRange(Begin).getBegin()) {
393 BeginExpansions[SM.getFileID(Begin)] = Begin;
394 }
395 // Move up the stack of expansion locations for the end until we find the
396 // location in BeginExpansions with that has the same file id.
397 for (SourceLocation End = R.getEnd(); End.isValid();
398 End = End.isFileID() ? includeHashLoc(SM.getFileID(End), SM)
399 : toTokenRange(SM.getImmediateExpansionRange(End),
400 SM, LangOpts)
401 .getEnd()) {
402 auto It = BeginExpansions.find(SM.getFileID(End));
403 if (It != BeginExpansions.end()) {
404 if (SM.getFileOffset(It->second) > SM.getFileOffset(End))
405 return SourceLocation();
406 return {It->second, End};
407 }
408 }
409 return SourceRange();
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000410}
411
412// Find an expansion range (not necessarily immediate) the ends of which are in
413// the same file id.
414static SourceRange
415getExpansionTokenRangeInSameFile(SourceLocation Loc, const SourceManager &SM,
416 const LangOptions &LangOpts) {
Sam McCallc791d852019-08-27 08:44:06 +0000417 return rangeInCommonFile(
418 toTokenRange(SM.getImmediateExpansionRange(Loc), SM, LangOpts), SM,
419 LangOpts);
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000420}
Sam McCallc791d852019-08-27 08:44:06 +0000421
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000422// Returns the file range for a given Location as a Token Range
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000423// This is quite similar to getFileLoc in SourceManager as both use
424// getImmediateExpansionRange and getImmediateSpellingLoc (for macro IDs).
425// However:
426// - We want to maintain the full range information as we move from one file to
427// the next. getFileLoc only uses the BeginLoc of getImmediateExpansionRange.
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000428// - We want to split '>>' tokens as the lexer parses the '>>' in nested
429// template instantiations as a '>>' instead of two '>'s.
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000430// There is also getExpansionRange but it simply calls
431// getImmediateExpansionRange on the begin and ends separately which is wrong.
432static SourceRange getTokenFileRange(SourceLocation Loc,
433 const SourceManager &SM,
434 const LangOptions &LangOpts) {
435 SourceRange FileRange = Loc;
436 while (!FileRange.getBegin().isFileID()) {
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000437 if (SM.isMacroArgExpansion(FileRange.getBegin())) {
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000438 FileRange = unionTokenRange(
439 SM.getImmediateSpellingLoc(FileRange.getBegin()),
440 SM.getImmediateSpellingLoc(FileRange.getEnd()), SM, LangOpts);
Sam McCallc791d852019-08-27 08:44:06 +0000441 assert(SM.isWrittenInSameFile(FileRange.getBegin(), FileRange.getEnd()));
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000442 } else {
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000443 SourceRange ExpansionRangeForBegin =
444 getExpansionTokenRangeInSameFile(FileRange.getBegin(), SM, LangOpts);
445 SourceRange ExpansionRangeForEnd =
446 getExpansionTokenRangeInSameFile(FileRange.getEnd(), SM, LangOpts);
Sam McCallc791d852019-08-27 08:44:06 +0000447 if (ExpansionRangeForBegin.isInvalid() ||
448 ExpansionRangeForEnd.isInvalid())
449 return SourceRange();
450 assert(SM.isWrittenInSameFile(ExpansionRangeForBegin.getBegin(),
451 ExpansionRangeForEnd.getBegin()) &&
Shaurya Gupta8fbb6ce2019-08-06 17:01:12 +0000452 "Both Expansion ranges should be in same file.");
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000453 FileRange = unionTokenRange(ExpansionRangeForBegin, ExpansionRangeForEnd,
454 SM, LangOpts);
455 }
456 }
457 return FileRange;
458}
459
Haojian Wu6ae86ea2019-07-19 08:33:39 +0000460bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM) {
461 return Loc.isValid() && SM.isWrittenInMainFile(SM.getExpansionLoc(Loc));
462}
463
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000464llvm::Optional<SourceRange> toHalfOpenFileRange(const SourceManager &SM,
Ilya Biryukov43998782019-01-31 21:30:05 +0000465 const LangOptions &LangOpts,
466 SourceRange R) {
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000467 SourceRange R1 = getTokenFileRange(R.getBegin(), SM, LangOpts);
468 if (!isValidFileRange(SM, R1))
Ilya Biryukov43998782019-01-31 21:30:05 +0000469 return llvm::None;
Ilya Biryukov43998782019-01-31 21:30:05 +0000470
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000471 SourceRange R2 = getTokenFileRange(R.getEnd(), SM, LangOpts);
472 if (!isValidFileRange(SM, R2))
Ilya Biryukov43998782019-01-31 21:30:05 +0000473 return llvm::None;
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000474
Sam McCallc791d852019-08-27 08:44:06 +0000475 SourceRange Result =
476 rangeInCommonFile(unionTokenRange(R1, R2, SM, LangOpts), SM, LangOpts);
Shaurya Gupta0d26d6f2019-07-12 11:42:31 +0000477 unsigned TokLen = getTokenLengthAtLoc(Result.getEnd(), SM, LangOpts);
478 // Convert from closed token range to half-open (char) range
479 Result.setEnd(Result.getEnd().getLocWithOffset(TokLen));
480 if (!isValidFileRange(SM, Result))
481 return llvm::None;
482
Ilya Biryukov43998782019-01-31 21:30:05 +0000483 return Result;
484}
485
486llvm::StringRef toSourceCode(const SourceManager &SM, SourceRange R) {
487 assert(isValidFileRange(SM, R));
488 bool Invalid = false;
489 auto *Buf = SM.getBuffer(SM.getFileID(R.getBegin()), &Invalid);
490 assert(!Invalid);
491
492 size_t BeginOffset = SM.getFileOffset(R.getBegin());
493 size_t EndOffset = SM.getFileOffset(R.getEnd());
494 return Buf->getBuffer().substr(BeginOffset, EndOffset - BeginOffset);
495}
496
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000497llvm::Expected<SourceLocation> sourceLocationInMainFile(const SourceManager &SM,
498 Position P) {
499 llvm::StringRef Code = SM.getBuffer(SM.getMainFileID())->getBuffer();
500 auto Offset =
501 positionToOffset(Code, P, /*AllowColumnBeyondLineLength=*/false);
502 if (!Offset)
503 return Offset.takeError();
504 return SM.getLocForStartOfFile(SM.getMainFileID()).getLocWithOffset(*Offset);
505}
506
Ilya Biryukov71028b82018-03-12 15:28:22 +0000507Range halfOpenToRange(const SourceManager &SM, CharSourceRange R) {
508 // Clang is 1-based, LSP uses 0-based indexes.
509 Position Begin = sourceLocToPosition(SM, R.getBegin());
510 Position End = sourceLocToPosition(SM, R.getEnd());
511
512 return {Begin, End};
513}
514
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000515std::pair<size_t, size_t> offsetToClangLineColumn(llvm::StringRef Code,
Sam McCalla4962cc2018-04-27 11:59:28 +0000516 size_t Offset) {
517 Offset = std::min(Code.size(), Offset);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000518 llvm::StringRef Before = Code.substr(0, Offset);
Sam McCalla4962cc2018-04-27 11:59:28 +0000519 int Lines = Before.count('\n');
520 size_t PrevNL = Before.rfind('\n');
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000521 size_t StartOfLine = (PrevNL == llvm::StringRef::npos) ? 0 : (PrevNL + 1);
Sam McCalla4962cc2018-04-27 11:59:28 +0000522 return {Lines + 1, Offset - StartOfLine + 1};
523}
524
Ilya Biryukov43998782019-01-31 21:30:05 +0000525std::pair<StringRef, StringRef> splitQualifiedName(StringRef QName) {
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000526 size_t Pos = QName.rfind("::");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000527 if (Pos == llvm::StringRef::npos)
528 return {llvm::StringRef(), QName};
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000529 return {QName.substr(0, Pos + 2), QName.substr(Pos + 2)};
530}
531
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000532TextEdit replacementToEdit(llvm::StringRef Code,
533 const tooling::Replacement &R) {
Eric Liu9133ecd2018-05-11 12:12:08 +0000534 Range ReplacementRange = {
535 offsetToPosition(Code, R.getOffset()),
536 offsetToPosition(Code, R.getOffset() + R.getLength())};
537 return {ReplacementRange, R.getReplacementText()};
538}
539
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000540std::vector<TextEdit> replacementsToEdits(llvm::StringRef Code,
Eric Liu9133ecd2018-05-11 12:12:08 +0000541 const tooling::Replacements &Repls) {
542 std::vector<TextEdit> Edits;
543 for (const auto &R : Repls)
544 Edits.push_back(replacementToEdit(Code, R));
545 return Edits;
546}
547
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000548llvm::Optional<std::string> getCanonicalPath(const FileEntry *F,
549 const SourceManager &SourceMgr) {
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000550 if (!F)
551 return None;
Simon Marchi25f1f732018-08-10 22:27:53 +0000552
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000553 llvm::SmallString<128> FilePath = F->getName();
554 if (!llvm::sys::path::is_absolute(FilePath)) {
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000555 if (auto EC =
Duncan P. N. Exon Smithdb8a7422019-03-26 22:32:06 +0000556 SourceMgr.getFileManager().getVirtualFileSystem().makeAbsolute(
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000557 FilePath)) {
558 elog("Could not turn relative path '{0}' to absolute: {1}", FilePath,
559 EC.message());
Sam McCallc008af62018-10-20 15:30:37 +0000560 return None;
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000561 }
562 }
Simon Marchi25f1f732018-08-10 22:27:53 +0000563
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000564 // Handle the symbolic link path case where the current working directory
565 // (getCurrentWorkingDirectory) is a symlink./ We always want to the real
566 // file path (instead of the symlink path) for the C++ symbols.
567 //
568 // Consider the following example:
569 //
570 // src dir: /project/src/foo.h
571 // current working directory (symlink): /tmp/build -> /project/src/
572 //
573 // The file path of Symbol is "/project/src/foo.h" instead of
574 // "/tmp/build/foo.h"
Harlan Haskinsa02f8572019-08-01 21:32:01 +0000575 if (auto Dir = SourceMgr.getFileManager().getDirectory(
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000576 llvm::sys::path::parent_path(FilePath))) {
577 llvm::SmallString<128> RealPath;
Harlan Haskinsa02f8572019-08-01 21:32:01 +0000578 llvm::StringRef DirName = SourceMgr.getFileManager().getCanonicalName(*Dir);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000579 llvm::sys::path::append(RealPath, DirName,
580 llvm::sys::path::filename(FilePath));
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000581 return RealPath.str().str();
Simon Marchi25f1f732018-08-10 22:27:53 +0000582 }
583
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000584 return FilePath.str().str();
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000585}
586
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +0000587TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M,
588 const LangOptions &L) {
589 TextEdit Result;
590 Result.range =
591 halfOpenToRange(M, Lexer::makeFileCharRange(FixIt.RemoveRange, M, L));
592 Result.newText = FixIt.CodeToInsert;
593 return Result;
594}
595
Haojian Wuaa3ed5a2019-01-25 15:14:03 +0000596bool isRangeConsecutive(const Range &Left, const Range &Right) {
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +0000597 return Left.end.line == Right.start.line &&
598 Left.end.character == Right.start.character;
599}
600
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000601FileDigest digest(llvm::StringRef Content) {
Sam McCall674d8a92019-07-08 11:33:17 +0000602 uint64_t Hash{llvm::xxHash64(Content)};
603 FileDigest Result;
604 for (unsigned I = 0; I < Result.size(); ++I) {
605 Result[I] = uint8_t(Hash);
606 Hash >>= 8;
607 }
608 return Result;
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000609}
610
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000611llvm::Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID) {
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000612 bool Invalid = false;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000613 llvm::StringRef Content = SM.getBufferData(FID, &Invalid);
Kadir Cetinkayad08eab42018-11-27 16:08:53 +0000614 if (Invalid)
615 return None;
616 return digest(Content);
617}
618
Eric Liudd662772019-01-28 14:01:55 +0000619format::FormatStyle getFormatStyleForFile(llvm::StringRef File,
620 llvm::StringRef Content,
621 llvm::vfs::FileSystem *FS) {
622 auto Style = format::getStyle(format::DefaultFormatStyle, File,
623 format::DefaultFallbackStyle, Content, FS);
624 if (!Style) {
625 log("getStyle() failed for file {0}: {1}. Fallback is LLVM style.", File,
626 Style.takeError());
627 Style = format::getLLVMStyle();
628 }
629 return *Style;
630}
631
Haojian Wu12e194c2019-02-06 15:24:50 +0000632llvm::Expected<tooling::Replacements>
633cleanupAndFormat(StringRef Code, const tooling::Replacements &Replaces,
634 const format::FormatStyle &Style) {
635 auto CleanReplaces = cleanupAroundReplacements(Code, Replaces, Style);
636 if (!CleanReplaces)
637 return CleanReplaces;
638 return formatReplacements(Code, std::move(*CleanReplaces), Style);
639}
640
Sam McCallc316b222019-04-26 07:45:49 +0000641template <typename Action>
642static void lex(llvm::StringRef Code, const format::FormatStyle &Style,
643 Action A) {
644 // FIXME: InMemoryFileAdapter crashes unless the buffer is null terminated!
645 std::string NullTerminatedCode = Code.str();
646 SourceManagerForFile FileSM("dummy.cpp", NullTerminatedCode);
Eric Liu00d99bd2019-04-11 09:36:36 +0000647 auto &SM = FileSM.get();
648 auto FID = SM.getMainFileID();
649 Lexer Lex(FID, SM.getBuffer(FID), SM, format::getFormattingLangOpts(Style));
650 Token Tok;
651
Sam McCallc316b222019-04-26 07:45:49 +0000652 while (!Lex.LexFromRawLexer(Tok))
653 A(Tok);
654}
655
656llvm::StringMap<unsigned> collectIdentifiers(llvm::StringRef Content,
657 const format::FormatStyle &Style) {
Eric Liu00d99bd2019-04-11 09:36:36 +0000658 llvm::StringMap<unsigned> Identifiers;
Sam McCallc316b222019-04-26 07:45:49 +0000659 lex(Content, Style, [&](const clang::Token &Tok) {
Eric Liu00d99bd2019-04-11 09:36:36 +0000660 switch (Tok.getKind()) {
661 case tok::identifier:
662 ++Identifiers[Tok.getIdentifierInfo()->getName()];
663 break;
664 case tok::raw_identifier:
665 ++Identifiers[Tok.getRawIdentifier()];
666 break;
667 default:
Sam McCallc316b222019-04-26 07:45:49 +0000668 break;
Eric Liu00d99bd2019-04-11 09:36:36 +0000669 }
Sam McCallc316b222019-04-26 07:45:49 +0000670 });
Eric Liu00d99bd2019-04-11 09:36:36 +0000671 return Identifiers;
672}
673
Sam McCallc316b222019-04-26 07:45:49 +0000674namespace {
675enum NamespaceEvent {
676 BeginNamespace, // namespace <ns> {. Payload is resolved <ns>.
677 EndNamespace, // } // namespace <ns>. Payload is resolved *outer* namespace.
678 UsingDirective // using namespace <ns>. Payload is unresolved <ns>.
679};
680// Scans C++ source code for constructs that change the visible namespaces.
681void parseNamespaceEvents(
682 llvm::StringRef Code, const format::FormatStyle &Style,
683 llvm::function_ref<void(NamespaceEvent, llvm::StringRef)> Callback) {
684
685 // Stack of enclosing namespaces, e.g. {"clang", "clangd"}
686 std::vector<std::string> Enclosing; // Contains e.g. "clang", "clangd"
687 // Stack counts open braces. true if the brace opened a namespace.
688 std::vector<bool> BraceStack;
689
690 enum {
691 Default,
692 Namespace, // just saw 'namespace'
693 NamespaceName, // just saw 'namespace' NSName
694 Using, // just saw 'using'
695 UsingNamespace, // just saw 'using namespace'
696 UsingNamespaceName, // just saw 'using namespace' NSName
697 } State = Default;
698 std::string NSName;
699
700 lex(Code, Style, [&](const clang::Token &Tok) {
701 switch(Tok.getKind()) {
702 case tok::raw_identifier:
703 // In raw mode, this could be a keyword or a name.
704 switch (State) {
705 case UsingNamespace:
706 case UsingNamespaceName:
707 NSName.append(Tok.getRawIdentifier());
708 State = UsingNamespaceName;
709 break;
710 case Namespace:
711 case NamespaceName:
712 NSName.append(Tok.getRawIdentifier());
713 State = NamespaceName;
714 break;
715 case Using:
716 State =
717 (Tok.getRawIdentifier() == "namespace") ? UsingNamespace : Default;
718 break;
719 case Default:
720 NSName.clear();
721 if (Tok.getRawIdentifier() == "namespace")
722 State = Namespace;
723 else if (Tok.getRawIdentifier() == "using")
724 State = Using;
725 break;
726 }
727 break;
728 case tok::coloncolon:
729 // This can come at the beginning or in the middle of a namespace name.
730 switch (State) {
731 case UsingNamespace:
732 case UsingNamespaceName:
733 NSName.append("::");
734 State = UsingNamespaceName;
735 break;
736 case NamespaceName:
737 NSName.append("::");
738 State = NamespaceName;
739 break;
740 case Namespace: // Not legal here.
741 case Using:
742 case Default:
743 State = Default;
744 break;
745 }
746 break;
747 case tok::l_brace:
748 // Record which { started a namespace, so we know when } ends one.
749 if (State == NamespaceName) {
750 // Parsed: namespace <name> {
751 BraceStack.push_back(true);
752 Enclosing.push_back(NSName);
753 Callback(BeginNamespace, llvm::join(Enclosing, "::"));
754 } else {
755 // This case includes anonymous namespaces (State = Namespace).
756 // For our purposes, they're not namespaces and we ignore them.
757 BraceStack.push_back(false);
758 }
759 State = Default;
760 break;
761 case tok::r_brace:
762 // If braces are unmatched, we're going to be confused, but don't crash.
763 if (!BraceStack.empty()) {
764 if (BraceStack.back()) {
765 // Parsed: } // namespace
766 Enclosing.pop_back();
767 Callback(EndNamespace, llvm::join(Enclosing, "::"));
768 }
769 BraceStack.pop_back();
770 }
771 break;
772 case tok::semi:
773 if (State == UsingNamespaceName)
774 // Parsed: using namespace <name> ;
775 Callback(UsingDirective, llvm::StringRef(NSName));
776 State = Default;
777 break;
778 default:
779 State = Default;
780 break;
781 }
782 });
783}
784
785// Returns the prefix namespaces of NS: {"" ... NS}.
786llvm::SmallVector<llvm::StringRef, 8> ancestorNamespaces(llvm::StringRef NS) {
787 llvm::SmallVector<llvm::StringRef, 8> Results;
788 Results.push_back(NS.take_front(0));
789 NS.split(Results, "::", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
790 for (llvm::StringRef &R : Results)
791 R = NS.take_front(R.end() - NS.begin());
792 return Results;
793}
794
795} // namespace
796
797std::vector<std::string> visibleNamespaces(llvm::StringRef Code,
798 const format::FormatStyle &Style) {
799 std::string Current;
800 // Map from namespace to (resolved) namespaces introduced via using directive.
801 llvm::StringMap<llvm::StringSet<>> UsingDirectives;
802
803 parseNamespaceEvents(Code, Style,
804 [&](NamespaceEvent Event, llvm::StringRef NS) {
805 switch (Event) {
806 case BeginNamespace:
807 case EndNamespace:
808 Current = NS;
809 break;
810 case UsingDirective:
811 if (NS.consume_front("::"))
812 UsingDirectives[Current].insert(NS);
813 else {
814 for (llvm::StringRef Enclosing :
815 ancestorNamespaces(Current)) {
816 if (Enclosing.empty())
817 UsingDirectives[Current].insert(NS);
818 else
819 UsingDirectives[Current].insert(
820 (Enclosing + "::" + NS).str());
821 }
822 }
823 break;
824 }
825 });
826
827 std::vector<std::string> Found;
828 for (llvm::StringRef Enclosing : ancestorNamespaces(Current)) {
829 Found.push_back(Enclosing);
830 auto It = UsingDirectives.find(Enclosing);
831 if (It != UsingDirectives.end())
832 for (const auto& Used : It->second)
833 Found.push_back(Used.getKey());
834 }
835
Sam McCallc316b222019-04-26 07:45:49 +0000836 llvm::sort(Found, [&](const std::string &LHS, const std::string &RHS) {
837 if (Current == RHS)
838 return false;
839 if (Current == LHS)
840 return true;
841 return LHS < RHS;
842 });
843 Found.erase(std::unique(Found.begin(), Found.end()), Found.end());
844 return Found;
845}
846
Sam McCall9fb22b22019-05-06 10:25:10 +0000847llvm::StringSet<> collectWords(llvm::StringRef Content) {
848 // We assume short words are not significant.
849 // We may want to consider other stopwords, e.g. language keywords.
850 // (A very naive implementation showed no benefit, but lexing might do better)
851 static constexpr int MinWordLength = 4;
852
853 std::vector<CharRole> Roles(Content.size());
854 calculateRoles(Content, Roles);
855
856 llvm::StringSet<> Result;
857 llvm::SmallString<256> Word;
858 auto Flush = [&] {
859 if (Word.size() >= MinWordLength) {
860 for (char &C : Word)
861 C = llvm::toLower(C);
862 Result.insert(Word);
863 }
864 Word.clear();
865 };
866 for (unsigned I = 0; I < Content.size(); ++I) {
867 switch (Roles[I]) {
868 case Head:
869 Flush();
870 LLVM_FALLTHROUGH;
871 case Tail:
872 Word.push_back(Content[I]);
873 break;
874 case Unknown:
875 case Separator:
876 Flush();
877 break;
878 }
879 }
880 Flush();
881
882 return Result;
883}
884
Haojian Wu9d34f452019-07-01 09:26:48 +0000885llvm::Optional<DefinedMacro> locateMacroAt(SourceLocation Loc,
886 Preprocessor &PP) {
887 const auto &SM = PP.getSourceManager();
888 const auto &LangOpts = PP.getLangOpts();
889 Token Result;
890 if (Lexer::getRawToken(SM.getSpellingLoc(Loc), Result, SM, LangOpts, false))
891 return None;
892 if (Result.is(tok::raw_identifier))
893 PP.LookUpIdentifierInfo(Result);
894 IdentifierInfo *IdentifierInfo = Result.getIdentifierInfo();
895 if (!IdentifierInfo || !IdentifierInfo->hadMacroDefinition())
896 return None;
897
898 std::pair<FileID, unsigned int> DecLoc = SM.getDecomposedExpansionLoc(Loc);
899 // Get the definition just before the searched location so that a macro
900 // referenced in a '#undef MACRO' can still be found.
901 SourceLocation BeforeSearchedLocation =
902 SM.getMacroArgExpandedLocation(SM.getLocForStartOfFile(DecLoc.first)
903 .getLocWithOffset(DecLoc.second - 1));
904 MacroDefinition MacroDef =
905 PP.getMacroDefinitionAtLoc(IdentifierInfo, BeforeSearchedLocation);
906 if (auto *MI = MacroDef.getMacroInfo())
907 return DefinedMacro{IdentifierInfo->getName(), MI};
908 return None;
909}
910
Sam McCallb536a2a2017-12-19 12:23:48 +0000911} // namespace clangd
912} // namespace clang